JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

What is String Interpolation in JavaScript?

Template literals use string interpolation to replace placeholders (${}) with their evaluated values. ${expression} is a placeholder. The expression used inside the placeholder is evaluated at runtime. The evaluated value is interpolated into the string. Before you understand the string interpolation in detail, you must be aware of creating a string using template literals.

Instead of single quotes or double quotes, when a string is surrounded by backtick(`), then template literal is created.

let str = `I am learning JavaScript`;

You might think of why there is a need for template literals if single and double quotes are already present in JavaScript. There are two reasons because of which template literals are introduced in JavaScript.

The first reason is when a string concatenation involves variables, then the chances of making mistakes increase. Let's understand this with the help of an example:

let firstNumber = 2;
let secondNumber = 3;
let addition = "The sum of + firstNumber + " and " + secondNumber + " is " + (firstNumber + secondNumber);

As you can see that the code is difficult to debug and understand. When you use string interpolation, your code becomes less error-prone and easy to debug. Let's rewrite the same code using string interpolation.

let firstNumber = 2;
let secondNumber = 3;
let addition = `The sum of + ${firstNumber} and ${secondNumber} is ${firstNumber + secondNumber}`;

Another reason for the introduction of template literals is the ease of creating a multiline string. If you want to learn more about template literals, refer to What are template literals in JavaScript?

Recommended Posts