Template Literals

Image taken from Unsplash

Template Literals


Template literals or template strings is a new way to concatenate strings in ES6. Let's take a look at code example below.

This is how we create greetings function that will greet the given name in traditional syntax.

// traditional
var greetings = function (name) {
  return 'Hello ' +  name;
};
console.log(greetings('Bambang')); // 'hello Bambang'

Now, let's refactor to template literals!

// es6
const greetings = (name) => `hello ${name}`;
console.log(greetings('Bambang')); // 'hello Bambang'

With template literals, our code looks more structured. We don't need the + sign anymore and we can use ${} to call variables.