Skip to content

How to insert variables in JavaScript string? | Example code

  • by

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading