String Interpolation in JavaScript

What is String Interpolation?

String interpolationis a process in JavaScript that is used to embed an expression, variable, or function into a string of text. With the help of this we can embed an expression and to embed an expression we use the template literals or backticks (`) instead of normal quotes. The template literal syntax has a dollar sign that is followed by curly brackets in JavaScript. We can write the expression or mathematical calculation inside the curly brackets. In simple words, by using a String interpolation we can make multi-line strings without the need of an escape character.

Key Points on String Interpolation:

Syntax of String Interpolation:


let name = "John";
let greeting = `Hello, ${name}!`;  // String interpolation

Example of String Interpolation:

This example demonstrates how to use string interpolation to embed variables inside a string.

Example


let firstName = "Jane";
let lastName = "Doe";
let fullName = `${firstName} ${lastName}`;
console.log(fullName);  // Outputs: "Jane Doe"

Output

Jane Doe

Expressions in Template Literals:

In addition to embedding variables, template literals can contain any JavaScript expression, such as mathematical operations or function calls.

Example with Expressions


let num1 = 5;
let num2 = 10;
let result = `The sum is: ${num1 + num2}`;
console.log(result);  // Outputs: "The sum is: 15"

Output

The sum is: 15

Advantages of String Interpolation:

Template Literals vs Concatenation:

In traditional string concatenation, you use the + operator to combine variables and strings. However, string interpolation with template literals is more elegant and reduces potential errors.

For example, with concatenation:

let greeting = "Hello, " + name + "!";

With string interpolation:

let greeting = `Hello, ${name}!`;

Template literals make the code shorter, cleaner, and easier to read.