This tutorial will explain what string interpolation is and how to use it in JavaScript. This tutorial will also compare strings created using interpolation to strings created by concatenation to show the benefits of using string interpolation.
String Concatenation
Concatenation needed to be used before string interpolation was introduced in JavaScript. To create a string with concatenation to show the values of variables, each string needs to use the plus sign (+) character to join strings to variables.
The below code shows an example of using string concatenation:
let fname = 'Jessie'; let mname = 'Andrew'; let lname = 'Edmisten'; let age = 44; let job = 'Software Developer'; let string1 = "Hello, my name is " + fname + " " + mname + " " + lname + ". I am " + age + " years old. I am a " + job + ".";
The above example shows that a string that displays the values of variables can be created using the + character to join the strings and variables. However, the example shows that it requires a lot of typing and it is prone to errors because it is easy to forget the spaces between variables and the period at the end.
String Interpolation
String interpolation became available in ES6 (ECMAScript 2015).
The following steps are needed to create a string using string interpolation:
- Wrap the string with backtick characters (`) instead of single quotes (‘) or double quotes (“). This is a template literal.
- Put variables in placeholders. The placeholders are ${}. Variables go in the opening ({) and closing braces (}). For example: ${variable1}
The below code shows an example of using string interpolation:
let fname = 'Jessie'; let mname = 'Andrew'; let lname = 'Edmisten'; let age = 44; let job = 'Software Developer'; let string1 = `Hello, my name is ${fname} ${mname} ${lname}. I am ${age} years old. I am a ${job}.`;
The above example shows that with string interpolation, the string is more concise making it easier to write, read, and less prone to mistakes.
The below example shows strings created by string interpolation and then string concatenation to display the improvement of string interpolation compared to string concatenation.
let fname = 'Jessie'; let mname = 'Andrew'; let lname = 'Edmisten'; let age = 44; let job = 'Software Developer'; let string1 = "Hello, my name is " + fname + " " + mname + " " + lname + ". I am " + age + " years old. I am a " + job + "."; let string2 = `Hello, my name is ${fname} ${mname} ${lname}. I am ${age} years old. I am a ${job}.`;
The above example shows that creating a string using interpolation is quicker to type and easier to read.
References:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
https://www.youtube.com/watch?v=5zLGtRU2vWU