Skip to content

JavaScript string format variables

  • by

JavaScript allows you to use template literals to format strings with variables. You can embed expressions inside a string using the ${expression} syntax, allowing you to use variables, functions, and arithmetic operations.

const name = 'Alice';
const age = 30;
const message = `Hello, my name is ${name} and I'm ${age} years old.`;
console.log(message);

This feature makes it easy to create dynamic and readable strings in your JavaScript code.

JavaScript string format variables example

Simple example code use valid JavaScript expression inside the ${} syntax, including variables, functions, and arithmetic operations.

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

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

Output:

JavaScript string format variables

How do I put variables inside javascript strings?

You can put variables inside JavaScript strings using template literals. Template literals are a feature introduced in ES6 that allows you to embed expressions inside a string using the ${expression} syntax.

const firstName = 'Alice';
const lastName = 'Smith';
const age = 30;
const occupation = 'developer';
const message = `Hi, my name is ${firstName} ${lastName}. I'm ${age} years old and I work as a ${occupation}.`;
console.log(message);

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 *