ES6 Template literals and string interpolation

In this post, we are going to learn javaScript ES6 Template literals and string interpolation with examples.

What is Template literal?


Template literal was Introduced in ES6(2015), Earlier, we used to create a string using single quotes (‘) or double quotes (“) quotes. But creating a string this way has some limited functionality. Template literal gives us more facility to create a dynamic string. Template literal use back-ticks(“) to define a string as shown below

string sentence = `Let work with string using Template literal`

Benefits using Template literal


  • String Substitution/Interpolation
  • Multiline String
  • Template Tag

1. String Substitution/Interpolation


The Template literal uses a placeholder to create string substitution and Interpolation is indicated by a dollar sign and curly braces ${`expression `}.

String substitution makes us combine variables’ names and expressions in the string. During run-time variables, names and expressions replace with their values. This is known as an interpolation in JavaScript.

String Substitution

const mycity = 'California'
const fullstring = `my city is ${mycity}`
console.log(fullstring)

Output

my city is California

Template literal with expression Interpolation

var num = 20
var num2 = 30
//Expression to add two numbers
console.log(`sum = ${num+num2}`);

//Expression to multiply two numbers
console.log(`multiplication = ${2 * (num + num2)} `);

Output

sum = 50
multiplication = 100 

Template Literal using function as Expression

In this example, we are passing the Sum() function as an expression in Template literal.

function sum()
{
  var num = 20,num2 = 30
  var sum = num+num2
  return sum;
}

console.log(`sum = ${sum()}`);

Output

sum = 50

2. Multi-line string


Prior to ES6 to span string in multi-line, we used to do some workaround by adding newline character(\n) end of each line.

Note: backslash(\) used to show the continuation of string onto multiple lines indication in string consider as white-space.

var announcement= 'This is announcement \n\
Pay attention';

console.log(announcement)

Output

This is announcement 
Pay attention

With ES6 Template literal, we can achieve the same just by pass string back-ticks(“) no need to use \n.

var announcement= `This is announcement 
Pay attention`;

console.log(announcement)

Output

This is announcement 
Pay attention

3.Tagged Template


The tag template is one of the strong features of Template Literal. We use a tagged template to create a Tag template that behaves like a function using template literal, unlike function Tag Template does not use parathesis() when it is called.

The first argument of the tag template function is an array of strings literal, remaining arguments describe expression.

Syntax

function TagTemplate(literals, ...expressions) {
//return string after computation
}
  • literal: The first parameter is an array of template strings. The array of template string is split using Expression as a separator.
  • Expression: The second parameter is the rest array parameter.

Return

  • The Tag template function performs any operation on given arguments and returns a string.

Example

In the above example, tagTemplatefun is a Template Tag Function. The first argument Strs is an array of a string literal. The second argument in this is the expression that we are passing as a country.

country = 'US'
function tagTemplatefun(strs, country) {
 let outString = ''
  strs.forEach((value, i) => {
    outString += `${strs[i]} ${country}`
  })
   return outString;
}

//calling the tag template function without parathesis
const paragraph = tagTemplatefun`The ${country} is a powerful country,  English is the native language of`;

console.log(paragraph);

Output

The  US is a powerful country,  English is native language of US

Example

In this example, we are printing array string of literal and Second parameters expression

let country = "US"
let capital = "washington"
let population  = "328.2 million"
 
function tagTemplatefun(strs, ...expressions) 
{
 
  console.log('Array of strings =',strs);  
  console.log('expressions=',expressions)
 
   
}
//calling the tag template function without para-thesis
tagTemplatefun`The ${country} is a powerful country,  capital is ${capital}${population}`;

Output

Array of strings = [ 'The ', ' is a powerful country,  capital is ', '', '' ]
expressions= [ 'US', 'washington', '328.2 million' ]

2. Library Used Tag Template


  • GraphQL
  • The Styled Components library use the Tag Template to define CSS-Style for React components
import styled from 'styled-components'

const Button = styled.button`
  background-color: red;
  color: blue;
`

Raw Strings

The String. raw method uses the Tagged Template function to get the raw version of the Template string and prevent any escape sequence from being processed.

Let us understand with example

let country = "US"
let capital = "washington"
let population  = "328.2 million"
 
var fullstring = String.raw `This is \n${country}, capital ${capital} population is  ${population}!`;
console.log(fullstring);

Output

This is \nUS, capital washington population is  328.2 million!