How to insert variables in JavaScript string?
Using Template literals you can put variables inside JavaScript strings.
Template literals can contain placeholders. These are indicated by the dollar sign and curly braces (${expression}
).
let a = `hello ${name}` // NOTE!!!!!!!! ` not ' or "
Note: from 2015 onwards, just use backticks for templating. The above code is a backtick, not a quote.
Complete HTML example code:
<html>
<body>
<script>
const name = "World"
const greeting = `Hello ${name}`;
alert(greeting);
</script>
</body>
</html>
Output:
Do comment if you have suggestions or doubts on this topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version