Skip to content

JavaScript string interpolation

  • by

In JavaScript, string interpolation refers to the process of embedding variables, expressions, or functions within a string literal. This is commonly done using template literals, which are enclosed in backticks ( ) instead of single or double quotes.

const name = "John";
console.log(`Hello, ${name}!`);

JavaScript string interpolation is a technique used to dynamically insert variable values into a string. When the code is executed, the variable values are replaced with their corresponding values, allowing for more readable and maintainable code.

JavaScript string interpolation example

Simple example code of several ways to achieve string interpolation using expressions inside string interpolation

<!DOCTYPE html>
<html>
<head>
  <script>
    const num1 = 10;
    const num2 = 5;
    console.log(`The sum of ${num1} and ${num2} is ${num1 + num2}.`);

  </script>
</head>
<body>
  
</body>
</html>

Output:

JavaScript string interpolation

You can concatenate strings and variables using the + operator.

const name = "John";
console.log("Hello, " + name + "!");

Or use the += operator to concatenate strings and variables.

const name = "John";
let message = "Hello, ";
message += name;
message += "!";
console.log(message);

This technique is commonly used in web development for tasks such as generating dynamic HTML content or building API requests.

Do comment if you have any doubts or suggestions on this JS string format topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *