javascript logo

Template literals

Template literals, introduced in ES6, are a new way to work with strings. You can create multi-line strings and insert different expressions.

Syntax:

A template literals are wrapped in backticks (``). instead of quotation marks. To insert an expression in a template a dollar sign and two curly braces are used(${}).

Single Line:

let newString = `This is a new string`;
console.log(newString);

Multi-Line:

let multiLineString = `This is line 1
This is line 2`;
console.log(multiLineString);

With an Expression:

let total = '$100';
let stringWithExpression = `The total price is ${total}.`;
console.log(stringWithExpression);
let price = 10;
let quantity = 5;

let totalPrice = `The total price is $${price * quantity}`;
console.log(totalPrice);

Tagged:

Tagged templates allow you to parse template literals with a function. The first argument of a tag function contains an array of string values. The remaining are related to the expressions.

function tagged(str) {
  console.log(str);
}

tagged`this is a test`;

//['this is a test']

A tagged function can do whatever calculations or comparisons you want to the arguments. Also these functions do not have to return a templated string.

let num1 = 20;
let num2 = 4;

function calculations(str, n1, n2){
  if (n1 > n2) {
    lessThan = `${n2} is less than ${n1}`;
  }
  
  return `These numbers are not equal because ${lessThan}`;
}

calculations`Are ${num1} and ${num2} equal?`;

//if you console log the arguments for this function 
//it will return an array of string and then the numeric values
//["Are ", " and ", " equal?", raw: Array(3)] 20 4