ES6 Basics Part 2 – Template Strings

ES6 can be thought of as a new version of Javascript. Currently most JS is ES5.

Over the next few articles, I’m going to break down the new features & syntax of ES6 into bite-size chunks. Please note that some experience writing JS is required to make full uses of these articles.

This is part 2 of many so please keep checking back for the next article in the series.
Part 1 – const & let can be found here.

Part 3 – Arrow Functions can be found here.
Part 4 – Classes can be found here.

Currently, to declare a template string or template literal in JS, variables need to be concatenated into the final string.

var string = "Hello " + username + ", Welcome back.";

 

With ES6 it is now a lot easier – when declaring the string it should now be wrapped in backticks (“). Within the new string, any variable can be injected into it using ${}.

var string = `Hello ${username}, Welcome back.`;

 

It is possible to include any JS expression inside ${}.

var string = `Here is a random number: ${Math.random()}`;

Why?

Complex strings are a lot easier to write & read – they are more like simple sentences with placeholders inside them instead of a mixture of opening and closing ” with + signs.

 

Check back shortly for the part 3 – Arrow Functions.

 

As not all browsers support ES6 code yet, Babel should be used to transpile (convert) the code into ES5 code.

Comments