JavaScript - Template literals

Template literals are a way to create strings in JavaScript that allow embedded expressions and multiline strings. They use **backticks (`)** instead of single (') or double ("`) quotes.

Key Features

  1. String Interpolation – insert variables or expressions directly.

  2. Multiline Strings – write strings that span multiple lines easily.

  3. Expression Evaluation – you can put any JavaScript expression inside ${...}.


Syntax

`string text ${expression} string text`

Example 1: Using Variables

const name = "Alice";
const age = 25;

const greeting = `Hello, my name is ${name} and I am ${age} years old.`;
console.log(greeting);

Output:

Hello, my name is Alice and I am 25 years old.

Example 2: Multiline Strings

const message = `This is a
multiline string
using template literals.`;

console.log(message);

Output:

This is a
multiline string
using template literals.

Example 3: Expressions Inside Template Literals

const a = 5;
const b = 10;

console.log(`The sum of ${a} and ${b} is ${a + b}.`);

Output:

The sum of 5 and 10 is 15.

Template literals make string handling in JS much cleaner compared to traditional concatenation with +.