Advanced interpolation

Executing JavaScript expressions or functions within the template literals. Advanced interpolation allows for more complex operations within the template literals. We can execute JavaScript expressions or call functions directly inside the ${} placeholders. This approach enables dynamic string generation based on calculations, conditionals, or function results.

Syntax:

`string text ${expression or function()} string text`

Example: This example shows the advanced interpolation by adding the two numbers in a single string using the ${} syntax.

JavaScript
// Using the advanced interpolation
const num1 = 10;
const num2 = 20;

// Using ${} syntax to add two numbers
const result = 
    `The sum of ${num1} and ${num2} is ${num1 + num2}.`;

// Output: The sum of 10 and 20 is 30.
console.log(result); 

Output
The sum of 10 and 20 is 30.

What is $ {} in JavaScript ?

In JavaScript, the ${} syntax is used within template literals, also known as template strings. Template literals, introduced in ECMAScript 6 (ES6), provide a convenient way to create strings with embedded expressions.

They are enclosed within backticks (`) instead of single quotes (”) or double quotes (“). Template literals support multi-line strings and allow for easy interpolation of variables and expressions within the string.

Table of Content

  • Basic interpolation
  • Advanced interpolation

Similar Reads

Basic interpolation

In basic interpolation, variables are directly inserted into the template string using ${} syntax. The expression inside ${} is evaluated, and its result is embedded into the string....

Advanced interpolation

Executing JavaScript expressions or functions within the template literals. Advanced interpolation allows for more complex operations within the template literals. We can execute JavaScript expressions or call functions directly inside the ${} placeholders. This approach enables dynamic string generation based on calculations, conditionals, or function results....