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

JavascriptStringVariablesConcatenation

Javascript Problem Overview


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}`);

Javascript Solutions


Solution 1 - Javascript

You're talking about template literals.

They allow for both multiline strings and string interpolation.

Multiline strings:

console.log(`foo
bar`);
// foo
// bar

String interpolation:

var foo = 'bar';
console.log(`Let's meet at the ${foo}`);
// Let's meet at the bar

Solution 2 - Javascript

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

Solution 3 - Javascript

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

Solution 4 - Javascript

It's used to reference a variable within string:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDarren JoyView Question on Stackoverflow
Solution 1 - JavascriptRick RunyonView Answer on Stackoverflow
Solution 2 - JavascriptJoel HView Answer on Stackoverflow
Solution 3 - JavascriptShalom EffiomView Answer on Stackoverflow
Solution 4 - JavascriptKhachikView Answer on Stackoverflow