Problem Statement
What are template literals in JavaScript?
Explanation
Template literals use backticks instead of quotes and provide powerful string features.
String interpolation lets you embed expressions using dollar sign and curly braces. The expression is evaluated and converted to a string.
Multi-line strings work naturally without needing escape characters.
You can embed any JavaScript expression, including function calls and calculations.
Template literals make string construction cleaner and more readable.
They were introduced in ES6 and are widely used in modern JavaScript.
Code Solution
SolutionRead Only
// Template literal syntax with backticks
const name = 'John';
const age = 30;
// String interpolation
const greeting = `Hello, my name is ${name} and I am ${age} years old`;
console.log(greeting);
// 'Hello, my name is John and I am 30 years old'
// Multi-line strings (no \n needed)
const multiLine = `
This is line 1
This is line 2
This is line 3
`;
console.log(multiLine);
// Expressions in template literals
const a = 5;
const b = 10;
console.log(`The sum is ${a + b}`); // 'The sum is 15'
console.log(`Double age: ${age * 2}`); // 'Double age: 60'
// Function calls
function getGreeting() {
return 'Hi';
}
console.log(`${getGreeting()}, ${name}!`); // 'Hi, John!'
// Nested template literals
const html = `
<div>
<h1>${name}</h1>
<p>Age: ${age}</p>
</div>
`;
// Compare with old way
const oldWay = 'Hello, my name is ' + name + ' and I am ' + age + ' years old';
// Conditional in template literal
const status = `User is ${age >= 18 ? 'adult' : 'minor'}`;
console.log(status); // 'User is adult'