Javascript Tutorial
Javascript Tutorial Introduction to Javascript JavaScript Code Editors & IDE JavaScript Hello World Example Javascript Syntax and Rules syntax_rules javascript_identifiers JavaScript Keywords & Reserved Words javascript_variables JavaScript Const JavaScript let vs var vs const Data Types in JavaScript JavaScript String Template Literals & String interpolation in JavaScript Tagged Templates in JavaScript String to Number in JavaScript Number Data Type in JavaScript NaN in JavaScript JavaScript Number Min & Max & Safe Values JavaScript EPSILON & Floating point precision Infinity in JavaScript JavaScript Bigint BigInt Vs Number in JavaScript Boolean Data Type in JavaScript Undefined in JavaScript Null in JavaScript Null vs Undefined in JavaScript JavaScript Operators Arithmetic Operators in JavaScript Unary plus & minus operators in JavaScript Increment & Decrement Operators in JavaScript Comparison or Relational operators in JavaScript Strict Equality (==) Loose Equality (===) in JavaScript Ternary Conditional Operator in JavaScript Logical Operators in JavaScript Bitwise Operators in JavaScript Assignment Operators in JavaScript Nullish Coalescing Operator in JavaScript Comma Operator in JavaScript Typeof JavaScript Operator Precedence in JavaScript JavaScript if, else & nested if statement Switch Statement in JavaScript While & Do While Loops in JavaScript For Loop in JavaScript Break statement in JavaScript Continue Statement in JavaScript Arrays in JavaScript Array Constructor in Javascript Sparse Array Vs Dense Array in JavaScript How to merge Arrays in JavaScript Array Methods in JavaScript Functions in JavaScript Function Parameters & Arguments in JavaScript JavaScript Default Parameters Pass by Value and Pass by Reference in Javascript Function Expression in Javascript Nested Functions in JavaScript Immediately-invoked Function Expressions (IIFE) JavaScript Callback Functions Arrow Functions in JavaScript Arguments Object In JavaScript Rest Parameters in JavaScript Objects in Javascript Create Objects in JavaScript JavaScript Object Properties Computed Property Names in JavaScript Object Literal in JavaScript Constructor Function & New Operator in JavaScript Delete Operator in JavaScript hasOwnProperty in JavaScript Using Getters and Setters in Javascript DefineProperty in JavaScript JavaScript Property Descriptors Enumerable, Writable & Configurable Object Destructuring in JavaScript Variable Scope in JavaScript Hoisting in JavaScript Lexical Scope & Closures in JavaScript This in JavaScript Global Object, Window & Globalthis in JavaScript Call function in Javascript Prototype In Javascript Prototype Inheritance in JavaScript Instanceof Operator in JavaScript Spread Operator in JavaScript

Template Literals & String interpolation in JavaScript

Template literals (or Template strings) in JavaScript are multi-line string literals that allow string interpolation. String interpolation allows us to include embedded expressions as part of the string . You can create multi-line strings, basic string formatting & tagged templates with Template strings. They are part of the ES2016/ES6 specification. Template strings are also called template literals. In this tutorial, we will learn about Template strings (or Literal) how to use it in Multiline Strings & string interpolation. We will also learn how to nest expressions and how to escape template literals using the backslash (\)

What is Template Strings

Template literals are literals delimited with backticks ` instead of single quote or double quotes.

The following is a example of template string.

                              
`Hello & Welcome to Tutorial on Template Strings`
 
                            
                            
                        

What makes them powerful is you can include a embedded expression within them. We must include the expression inside a dollar sign and curly braces (${expression}) .

In the following example ${name} is an expression. The JavaScript evaluates it and replaces its value in the its original position.

                              
`Hello ${name}, Welcome to tutorial on Template string`
 
                            
                            
                        

Let us now explore the some of the use cases for the Template Strings

Multiline Strings

The following is an example of creating a multiline string. Just hit enter and continue in the next line. The \n character automatically gets inserted in the string.

Example

                               
let sentence= `Javascript is the scripting language, 
that we use to make web pages interactive. 
It is written in plain text on the HTML page and runs in the browser`
 
console.log(sentence);
 
 
//**** output ****
 
//Javascript is the scripting language, 
//that we use to make web pages interactive. 
//It is written in plain text on the HTML page and runs in the browser
 
                            
                            
                        

The multiline strings without template strings are created by inserting a \n newline character (LF).

                               
let sentence= "Javascript is the scripting language,\n" +
"that we use to make web pages interactive.\n" +
"It is written in plain text on the HTML page and runs in the browser"
 
console.log(sentence);
 
 
//***output****
 
 
//Javascript is the scripting language,
//that we use to make web pages interactive.
//It is written in plain text on the HTML page and runs in the browser
                            
                            
                        

As we said earlier, the /n (LF) character is inserted when you use the template strings. Hence the following code is true.

                               
const str = `Line1
Line2`;
console.log(str);
console.log(str === 'Line1\nLine2');       // true
 
//***output***
//Line1
//Line2
//true
                            
                            
                        

String Interpolation

string interpolation (expression Interpolation) is the process of evaluating a string literal containing one or more expressions. It evaluates the expression and coerces the result into a string. The result is then is replaced in the original string.

Example

In the following example, $(playerName) is the expression. It is evaluated first and the resulting value Sachin Tendulkar is replaced at its place in the final string.

                               
let playerName = "Sachin Tendulkar";    
console.log(`${playerName} is the greatest cricketer of all time`)
 
 
 
//**** Output ****
//Sachin Tendulkar is the greatest cricketer of all time
                            
                            
                        

Multiple Expressions

                               
const firstName = 'Students';
const topic ="Template Literals"
 
console.log(`Hello ${firstName}!
Welcome to the ${topic} tutorial`);
 
 
//*** output ****
//Hello Students!
//Welcome to the Template Literals tutorial
                            
                            
                        

Using Expressions

The following example shows that you can use any expressions inside the template string. It uses the arithmetic expression ${a+b}

                               
let a=1;
let b=2;
console.log(`The addition of ${a} + ${b} is ${a+b}`);
 
 
//***output ****
//The addition of 1 + 2 is 3
                            
                            
                        

The following example uses the ternary conditional operator(?) in the template string.

                               
let m=11;
console.log(`The m is ${(m==10) ?'ten':'not ten'}`);
 
 
//*** output ****
//The m is not ten
                            
                            
                        
                                                
 const MAX = 100;
 
 function doSomeWork(x) {
   if (x > MAX) {
     throw new Error(`At most ${MAX} allowed: ${x}!`);
   }
 }
  
 doSomeWork(200)
                            
                            
                        

Nesting Expressions

You can nest expressions

                               
let x=10
let y=20
let varxy=`${x+y}`      //template string
console.log(`The addion of ${x} + ${y} is ${varxy}`);    //tempate string nested
 
 
//*** output ****
//The addion of 10 + 20 is 30
                            
                            
                        

The following example uses the ternary conditional operator(?) in the template string.

                               
let m=11;
console.log(`The m is ${(m==10) ?'ten':'not ten'}`);
 
 
//*** output ****
//The m is not ten
                            
                            
                        
                                                
 const MAX = 100;
 
 function doSomeWork(x) {
   if (x > MAX) {
     throw new Error(`At most ${MAX} allowed: ${x}!`);
   }
 }
  
 doSomeWork(200)
                            
                            
                        

Tagged Templates

Another use of the Template string is in Tagged Templates. We tag a Template string to a function. This allows us to customize the parsing of the template string using the tagged function.