JS Template Literals
In this page:
Basic Template Literals
Template literals are strings wrapped in backticks ` instead of quotes, and they let you embed variables and expressions directly inside the string using ${} syntax.
Example: Basic Template Literals
const name = "Sam";
console.log(`Hello, ${name}!`);
Expressions
Any valid JavaScript expression can go inside ${}, from a simple variable to a function call or arithmetic, and JavaScript evaluates it and converts the result to a string automatically.
Example: Expressions
const a = 2, b = 3;
console.log(`Sum: ${a + b}`);
Multiline Strings
Unlike regular strings, template literals can span multiple lines just by pressing enter inside the backticks, without needing explicit \n characters or string concatenation.
Example: Multiline Strings
const message = `Line one
Line two`;
console.log(message);
Nested Templates
Template literals can be nested inside each other's ${} expressions, which is useful for conditional formatting, like showing a different piece of text depending on a value.
Example: Nested Templates
const isAdmin = true;
console.log(`Role: ${isAdmin ? `Admin ${1}` : "User"}`);
Template Literal Benefits
Template literals remove the need for messy string concatenation with +, making code that mixes text and variables noticeably easier to read and less error-prone, especially once more than one or two variables are involved.
Example: Template Literal Benefits
const name = "Sam";
const age = 30;
console.log("Name: " + name + ", Age: " + age); // old way
console.log(`Name: ${name}, Age: ${age}`); // template literal
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: