What does ${} (dollar sign and curly braces) mean in a string in JavaScript?

Viewed 280844

I haven't seen anything here or on MDN. I'm sure I'm just missing something. There's got to be some documentation on this somewhere?

Functionally, it looks like it allows you to nest a variable inside a string without doing concatenation using the + operator. I'm looking for documentation on this feature.

Example:

var string = 'this is a string';

console.log(`Insert a string here: ${string}`);

6 Answers

As mentioned in a comment above, you can have expressions within the template strings/literals. Example:

const one = 1;
const two = 2;
const result = `One add two is ${one + two}`;
console.log(result); // output: One add two is 3

You can also perform Implicit Type Conversions with template literals. Example:

let fruits = ["mango","orange","pineapple","papaya"];

console.log(`My favourite fruits are ${fruits}`);
// My favourite fruits are mango,orange,pineapple,papaya

It's used to reference a variable within string:

let someVar = "World!"
console.log(`Hello ${someVar}`); // Output is Hello World!

const firstName = 'Sachin'; const age = 16 alert(${firstName} is ${age} years old)

//Sachin is 16 years old

It's used as a variable interpolation ${variable_name}

Related