JavaScript Template Strings

String Interpolation

String Interpolation is the way by which we can insert variables into a string. In JavaScript, We have two types of String Interpolation.

  • Traditional
  • ES6

Traditional Way

In traditional Javascript, a string is always enclosed within ” or ‘. Using double or single quotes we can write text on one line. There was no way to insert data into these strings. This kind of way looks very ugly.

var name = "xyz";
var age = 40;

console.log("Welcome " + name + " You are looking " + age + " years old"); 
//Welcome xyz You are looking 40 years old

ES6 Way

In Es6 we have a new type of string literal that is marked with backticks (`). Here we can write text new lines as well as we can insert data in between text strings.

var name = "xyz";
var age = 40;

console.log(`Welcome ${name} You are looking ${age} years old`); 
// Welcome xyz You are looking 40 years old.

Multi-line Strings

var name = "xyz",
    age = 40;

var str = `
Welcome ${name}
You are looking ${age} years
Welcome xyz
You are looking 40 years

About the Author: Pankaj Bisht