Learning JavaScript ES6: Part 2: Template Literals

Learning JavaScript ES6

JavaScript ES6 (ECMAScript 6) is a newer specification for JavaScript introduced in 2015 and adopted by most browsers starting in mid-2016. It added new syntax and a greater ability to use object-oriented programming in JavaScript.

Template Literals

In older versions of JavaScript, complex series of operations were required to make a string mixed of both existing content and variables. All of these needed to be concatenated together through using the plus, +, sign between them.

The concept of template literals helps with this very issue. Instead of concatenating different values, the use of template literals allows for writing code where values will be placed into the string during run-time.

Creating Template Literals

Template literals depend on two different syntax usages. The first is that a string which contains template literals must be set off using backticks around it. This differs from the normal single or double-quotes that would be around a string. The second is that variables must be contained within curly brackets and have a dollar sign in front of them.

Using Template Literals

The result of the use of a template literal is a string. This means that template literals can be used to display content made up of the values of variables. When used in a web development context, for example, this can be very helpful to dynamically create content.

Play with the example on repl.it!