About many things

Template literals in javascript

I want to write about another new thing that I found in javascript. Those are called Template literals and look like this:

`string text`

`string text line 1
 string text line 2`

`string text ${expression} string text`

tag `string text ${expression} string text`

Let’s see where we can use them.

Syntax

From sample above you case see that Template literals look like regular strings, but with some extra features and instead of double quotes you need to use back-ticks to declare them.

As a bonus you can define multi-line strings and embed any valid javascript expression in it. Let’s see few usages below.

Usages

Basic sample below uses template literal to pass name:

// Simple string substitution
var name = "Gevorg";
console.log(`Yo, ${name}!`);

// => "Yo, Gevorg!"

you can embed function calls:

function fn() { return "I am a result. Rarr"; }
console.log(`foo ${fn()} bar`);

//=> foo I am a result. Rarr bar.

or just any valid javascript expression:

var user = {name: 'Caitlin Potter'};
console.log(`Thanks for getting this into V8, ${user.name.toUpperCase()}.`);

// => "Thanks for getting this into V8, CAITLIN POTTER";

Tagged Templates

You can modify templates by placing function calls in front of them:

var a = 5;
var b = 10;

function tag(strings, ...values) {
  console.log(strings[0]); // "Hello "
  console.log(strings[1]); // " world "
  console.log(strings[2]); // ""
  console.log(values[0]);  // 15
  console.log(values[1]);  // 50

  return "Boom-boom chacka-chaka!";
}

tag`Hello ${ a + b } world ${ a * b }`;
// => "Boom-boom chacka-chaka!"
#javascript #es2015