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

Tagged Templates in JavaScript

The JavaScript Tagged Templates allow us to tag template strings or template literals using a function. Once tagged, we can parse the Templates strings using the tagged function. It allows us more control over how the templates are converted to a string.

Template strings

We can create a Template String in JavaScript (or Template Literals) by enclosing the string inside a back-tick. What makes the Template strings powerful is that we can include a expression inside them. The expression must be specified inside dollar sign and curly braces (${expression}). JavaScript evaluates the expression and coerces the result into a string. This allows us to create a dynamic string.

In the following example, we have included the expression ${playerName} inside the string. When we run the code ${playerName} is evaluated and its value Sachin Tendulkar is inserted 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
                            
                            
                        

But what if want to run some business logic and have more control over the transformation of the given string. This is where we use the Tagged Templates.

What is a Tagged Template?

The Tagged Template is a template string, to which we tag a function (attach a function). It consists of two parts. One is Template String and the other one is a function (which we call Tagged function). The Tagged function is where we write our custom logic to parse the template string.

How to Create a Tagged Template

To create a tagged template, First, we need to create a function. Then use it to tag the Template string by placing before it.

In the following example we create a function transform. The function just returns the message hi

We tag the Template string with the function. That is done by placing the function name before it without the customary (). Now this Template string is a tagged template.

When we run the code, you will see Hi in the output, which is what our tagged function returns.

                            
let message="Hello";
 
 //This is our tag function
 function transform() {                     
   return 'Hi';
 }
  
 //use the function to tag the template string
 console.log(transform`${message} world`);        
  
  
 //**** output ****
 //Hi
                            
                            
                        

But what if want to run some business logic and have more control over the transformation of the given string. This is where we use the Tagged Templates.

Useful References

Parameters to Tagged Function

The tagged function receives following arguments.

  1. The first argument to the function is the array of template strings. It is split using the expression as the separator.
  2. The evaluated expressions are the subsequent arguments.

Consider the following template string

                            
`Hello, ${firstName} ${lastName}. Welcome to ${topic} Tutorial`
                            
                            
                        

The first argument to the tag function is an array of strings (Strings).

The first element in the array is the string up to the first expression $(firstName), which is “Hello,”. The second element is the string between the first expression $(firstName) and the second expression $(lastName) i.e.a blank string. The third element is between the second expression $(lastName)and the third expression(${topic}) (${topic}). i.e. “. Welcome to”. And the last element is from the last expression ${topic} to the end of the string i.e. “Tutorial”

Hence our first argument is [ 'Hello, ', ' ', '. Welcome to ', ' Tutorial' ]

The expressions are evaluated and passed as the subsequent arguments in the order of occurrence.

Useful References
                            
let firstName  = "Sachin"
let lastName = "Tendulkar"
let topic = "JavaScript"
 
console.log(transform`Hello, ${firstName} ${lastName}. Welcome to ${topic} tutorial`);
 
 
function transform(strings, firstName,lastName,topic) {
  let str = strings[0]+ firstName+strings[1]+lastName+strings[2]+topic+strings[3];
  return str;
}
 
//Hello, Sachin Tendulkar. Welcome to JavaScript tutorial
                            
                            
                        

In the above example, we knew the number of arguments beforehand. But, if there are a variable number of expressions, then it would be better to make use of the rest operator as shown below

                            
let firstName = "Sachin"
let lastName = "Tendulkar"
let topic = "JavaScript"
 
function transform(strings, ... expr) {
  console.log(strings);
  console.log(expr);
  return "";
}
 
console.log(transform`Hello, ${firstName} ${lastName}. Welcome to ${topic} Tutorial`);
 
 
//['Hello, ', ' ', '. Welcome to ', ' Tutorial']
//['Sachin', 'Tendulkar', 'JavaScript']
 
                            
                            
                        

Now once we have the required arguments, we can use them in the function to fine-tune the output

                            
let firstName = "Sachin"
let lastName = "Tendulkar"
let topic = "JavaScript"
 
function transform(strings, ... expr) {
  let str = '';
  strings.forEach((string, i) => {
      str += string + (expr[i] || '');
  });
  return str;
}
 
console.log(transform`Welcome, ${firstName} ${lastName}. Learn ${topic} here`);
 
 
//Welcome, Sachin Tendulkar. Learn JavaScript here
 
                            
                            
                        

Note that the strings array is always be going to be one more than the expr array. Hence when we come to the last string in the loop, the expr would be undefined

Raw strings

The ES6 also has a useful method String.raw, which prevents escape characters from being interpreted. The backslash is a special character ( escape ) in JavaScript. When JavaScript encounters a backslash, it tries to escape the following character.

Take a look at the following example. The variable filePath contains several \. When we use this expression in Template string, the backslashes are removed from the output as JavaScript treats them as escape character.

                            
filePath = `C:\Development\profile\aboutme.html`;
console.log(`The file was uploaded from: ${filePath}`);
 
 
//OUTPUT
The file was uploaded from: C:Developmentprofileaboutme.html
 
 
                            
                            
                        

Here you can make use of String.raw tagged function to return the raw string.

                            
filePath =String.raw`C:\Development\profile\aboutme.html`;
console.log(`The file was uploaded from: ${filePath}`);
 
//OUTPUT
The file was uploaded from: C:\Development\profile\aboutme.html
 
 
                            
                            
                        

The following example shows how to use raw method inside the tagged function. In this case newline character \n is ignored.

                            
 
firstName="Sachin"
lastName="Tendulkar"
topic="JavaScript"
 
function transform(strings, ...expr) {
  let str = '';
  strings.raw.forEach((string, i) => {         //using strings.raw
      str += string + (expr[i] || '');
  });
  return str;
}
 
 
console.log(transform `Hello ${firstName} ${lastName} \n Welcome to ${topic} Tutorial`);
 
 
//OUTPUT 

                            
                            
                        

Without raw method, the \n is interpreted correctly and a new line is inserted in the output.

                            
function transform(strings, ...expr) {
  let str = '';
  strings.forEach((string, i) => {              //using strings
      str += string + (expr[i] || '');
  });
  return str;
}
 
 
//OUTPUT
//Hello Sachin Tendulkar 
//Welcome to JavaScript Tutorial                //newline
 
 


                        

Read More

  1. JavaScript Tutorial
  2. Data Types in JavaScript
  3. JavaScript String
  4. Template Strings & String Interpolation
  5. String to Number
  6. Number Data Type
  7. NaN in JavaScript
  8. Min, Max & Safe Values
  9. EPSILON & Floating Point Precision
  10. Infinity
  11. BigInt
  12. BintInt Vs Number
  13. Boolean Data Type
  14. Undefined