The addition of template literals in ECMAScript 6 (ES6) allows us to interpolate strings in JavaScript.
In simpler words, we can use placeholders to inject variables into a string. You can see an example of string interpolation using template literals in the snippet below:
const age = 4.5;
const earthAge = `Earth is estimated to be ${age} billion years old.`;
console.log(earthAge);
First of all, you’ll see that we are using backticks for template literals. Besides that, we also have the format of ${placeholder}
, which allows us to insert a dynamic value into the string. Anything inside ${}
is evaluated as JavaScript.
For instance, we could write Earth is estimated to be ${age + 10} billion years old.
, and it would work as if we did const age = 4.5 + 10;
.
#javascript #web-development #developer