Template Literals
Template Literals
π¨βπΌ Remember how tedious string concatenation was? Template literals make
combining strings and expressions much easier!
Instead of quotes, template literals use backticks:
console.log(`Hello, World!`)
What makes these so special is you don't have to escape quotes or even
newline characters:
console.log(`Hello,
World!`)
// Prints the same thing as: console.log('Hello,\nWorld!')
In addition, while you can still use string concatenation, you can embed any expression using
${expression}:console.log(`2 + 2 = ${2 + 2}`) // Prints: 2 + 2 = 4
console.log(`Hello, ${'World'}!`) // Prints: Hello, World!
π¨ Open
and complete the following tasks:
- Log a template literal that says "The answer is 42" using
${40 + 2} - Log a greeting that includes "Hello" and "TypeScript" in one template literal
- Log a math problem and its answer, like "10 times 5 equals 50"
π° The backtick key is usually in the top-left of your keyboard, below Escape.