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

JS Template Literals

Template literals are strings written with backticks that let you drop values right into a sentence, like a fill-in-the-blank. They can also stretch over several lines.
Syntax
javascript
const text = `text ${expression} more text`;

const multiLine = `line one
line two`;

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.

उदाहरण: 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.

उदाहरण: 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.

उदाहरण: Multiline Strings

javascript
// Declare the constant `message`, set to ``Line one`
const message = `Line one
Line two`;
// Print `message` to the console
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.

उदाहरण: 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.

उदाहरण: 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
Live Example
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}

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.