← Back to JavaScript Course | Chapter 5: ES6+ Features | Lesson 3 of 12

JS Template Literals

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

javascript
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

javascript
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

javascript
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

javascript
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

javascript
const name = "Sam";
const age = 30;
console.log("Name: " + name + ", Age: " + age); // old way
console.log(`Name: ${name}, Age: ${age}`); // template literal

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.