How to Use String Interpolation in JavaScript?

Estimated read time 1 min read

String interpolation is a way to embed expressions within string literals, allowing you to build strings from variables, expressions, and other values. In JavaScript, you can use template literals to achieve string interpolation.

Template literals are surrounded by backticks () instead of single or double quotes. Within a template literal, you can embed expressions by enclosing them within ${…}`. For example:

let name = "John";
let message = `Hello, ${name}!`;
console.log(message);  // outputs: "Hello, John!"

You can use any valid JavaScript expression within the ${...} syntax, including function calls, ternary operators, and arithmetic expressions. For example:

let x = 10;
let y = 20;
let result = `The sum of x and y is ${x + y}.`;
console.log(result);  // outputs: "The sum of x and y is 30."

You can also use template literals to define multiline strings, without having to use escape characters:

let multiline = `This is a
multiline string
created with template literals.`;
console.log(multiline);

Overall, string interpolation with template literals is a convenient and readable way to build strings in JavaScript.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply