JavaScript - Template (literals|strings) - Here Document

About

Template literals are string literals allowing embedded expressions.

Template literals enables:

in the same syntactic sugar than a bash expression.

Syntax

Template literals:

  • are enclosed by the back-tick
  • can contain place holders. These are indicated by the Dollar sign and curly braces ${expression}
  • can be tagged. They allow to parse template literals with a function.

\ is the escape character in template literals.

Example

Variable Substitution

variable substitution

var name='Nico';
console.log(`Hello ${name}`);

Back-tick Equality

console.log(`\`` === '`')

MultiLine

Without Template literals

console.log('string text line 1\n' +
'string text line 2');

With Template literals

console.log(`string text line 1
string text line 2`);

Concatenation vs Expression Substitution

Without Template literals

var a = 5;
var b = 10;
console.log('Fifteen is ' + (a + b) + 
' and\nnot ' + (2 * a + b) + '.');

With Template literals

var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b} and
not ${2 * a + b}.`);

Tag

Named Variable

var person = 'Nico'; // ${person}
var yearsOfExperience = 1; // ${yearsOfExperience}

var output = myTagFunction`that ${person} is a ${yearsOfExperience} in Javascript`; 
// that Nico is a NewBie in Javascript
console.log(output);

function myTagFunction(strings, personExp, yearExp) {

  var str0 = strings[0]; // "that "
  var str1 = strings[1]; // " is a "
  var str2 = strings[2]; // " in Javascript "

  if (yearExp> 3){
    levelStr = 'Medior';
  } else {
    levelStr = 'Newbie';
  }

  return str0 + personExp + str1 + levelStr + str2;

}

Unamed Variable (Positional and Inline)

function template(strings, ...keys) {
  return (function(...values) {
    var dict = values[values.length - 1] || {};
    var result = [strings[0]];
    keys.forEach(function(key, i) {
      var value = Number.isInteger(key) ? values[key] : dict[key];
      result.push(value, strings[i + 1]);
    });
    return result.join('');
  });
}

var t1Closure = template`${0}${1}${0}!`;
console.log(t1Closure('Y', 'A'));  // "YAY!"
var t2Closure = template`${0} ${'foo'}!`;
console.log(t2Closure('Hello', {foo: 'World'}));  // "Hello World!"

Documentation / Reference


Powered by ComboStrap