Template literals
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
A cleaner way to build strings
- Wrap a string in backticks
`and you can drop values straight in with${...}. - This is a template literal — much tidier than joining with lots of
+.
let name = "Ada";
let age = 15;
console.log(`${name} is ${age}`); // → Ada is 15
Any expression fits inside ${ }
- Whatever you write inside
${...}is worked out first, then dropped into the string.
let a = 3;
let b = 4;
console.log(`${a} + ${b} = ${a + b}`); // → 3 + 4 = 7
Watch out
- Backticks
`are not the same as quotes'or".${...}only works inside backticks. - Bonus: a backtick string can span several lines — handy for longer messages.
Common mistakes
- Template literals use backticks and
${...}:`Hi ${name}`, not quotes. - Inside
${...}you can put any expression.
Now you try
- Use backticks and
${...}. - Press Check answer to test it.
let name = "Sam". Use a template literal (backticks) to log Hello, Sam!.
Click Run to see the output here.
a is 3 and b is 4. Use a template literal to log 3 + 4 = 7 (put a + b inside ${ }).
Click Run to see the output here.
Use a template literal to log Total: 10, working out the 10 as 5 * 2 inside ${ }.
Click Run to see the output here.