Open In App

What is $ {} in JavaScript ?

Last Updated : 21 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

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.

Syntax:

`string text ${expression} string text`

Example: This example shows the basic interpolation by combining the name and age in a single string using the ${} syntax.

JavaScript
const name = "Geeks";
const age = 30;
const message = 
    `Hello, my name is ${name} and I am ${age} years old.`;
console.log(message);

Output
Hello, my name is Geeks and I am 30 years old.

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.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads