Template Strings

Description

This is used to define a string using backticks(``). It has many use cases. It can be used to embed expressions and variables into strings.

Example 1:

var me = `hello, my name is posh`;
console.log(me);
//Result will be; hello, my name is posh.

Example 2: It doesn't ignore line breaks or whitespaces.

var me = `hello, 
my name is posh`;
console.log(me);
//Result will be; hello, 
//my name is posh.

//Add more than one line break and even whitespaces;
var me = `hello, 

  my name is posh`;
console.log(me);
//Result will be; hello, 
//
//  my name is posh.

Example 3: Skip concatenation

//Using concatenation
function myInfo(name, age) {
    console.log("my name is " + name + " and I am " + age + " years old.")
}
myInfo("posh", 18);
//Result will be; my name is posh and I am 18 years old.

//Passing in variables with template literals
function myInfo(name, age){
    console.log(`my name is ${name} and I am ${age} years old.`)
}
myInfo("posh", 18);
//Result will be; my name is posh and I am 18 years old.

//Passing in expressions and variables with template literals;
function myInfo(name, age) {
    console.log(`my name is ${name} and I am ${10+18} years old.`)
}
myInfo("posh", 18);
//Result will be; my name is posh and I am 28 years old.
//Notice the argument 18, was ignored and the expression was calculated as the age.

//If no argument is passed for the age like so;
function myInfo(name, age){
    console.log(`my name is ${name} and I am ${10+18} years old.`)
}
myInfo("posh");
//Result will be; my name is posh and I am 28 years old.