Javascript – String Interpolation

OVERVIEW

An alternative to using string concatenation is to use string interpolation. String interpolation allows us to put variables in the string value which are then replaced by their values at runtime.

There are a couple of rules to follow. The string must be defined in backticks eg. ` . Strings which are defined using normal double quotes or single quotes do not handle string interpolation.

The sample code below shows an example of this. Note that you can put expressions or even call functions within the template string delimiters.

SAMPLE CODE

<html>
	<head><title>String Interpolation</title></head>

	<script>
		var number = 20;
		var cost = 5.00;
		var price = 100.00;
		var msg1 = "The price of " + number + " objects at a cost of " + cost + " each comes to " + price;
		document.write(msg1);

		var msg2 = `The price of ${number} objects at a cost of ${cost} each comes to ${price}`;
		document.write("<br>" + msg2);

		var msg3 = `The price of ${number} objects at a cost of ${cost} each comes to ${cost * number}`;
		document.write("<br>" + msg2);


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

The output is given below

The price of 20 objects at a cost of 5 each comes to 100
 The price of 20 objects at a cost of 5 each comes to 100
 The price of 20 objects at a cost of 5 each comes to 100 

Be the first to comment

Leave a Reply

Your email address will not be published.


*