Template Literals
This lesson covers new ways of interpolating strings and more, with template literals.
Template literals were called template strings prior to ES6… Let’s have a look at what’s changed in the way we interpolate strings in ES6.
Interpolating strings #
We used to write the following in ES5 in order to interpolate strings:
Press + to interact
var name = "Alberto";var greeting = 'Hello my name is ' + name;console.log(greeting);// Hello my name is Alberto
In ES6, we can use backticks to make our lives easier. We also need to wrap our variable names in ${}
Press + to interact
let name = "Alberto";const greeting = `Hello my name is ${name}`;console.log(greeting);// Hello my name is Alberto
Press + to interact
var a = 1;var b = 10;console.log('1 * 10 is ' + ( a * b));// 1 * 10 is 10
In ES6 we can use backticks to reduce our typing:
Press + to interact
var a = 1;var b = 10;console.log(`1 * 10 is ${a * b}`);// 1 * 10 is 10
...