HomeJAVASCRIPTWhat are template literals?

What are template literals?

Template literals in JavaScript are a special way of working with strings.
They were introduced in ES6 (ECMAScript 2015) and provide more powerful features compared to normal string literals (' ' or " ").

Template literals are written using backticks (`) instead of single (') or double (") quotes.


Features of Template Literals:

String Interpolation (Embedding Expressions)

  • You can embed variables or expressions directly inside a string using ${ }.

const name = "Himanshu"; 
const aage = 27; 
console.log(`My name is ${name} and I am ${age} years old.`); 

// Output: My name is Himanshu and I am 27 years old.

Multi-line Strings

  • Unlike normal strings, template literals allow you to write multi-line strings without using \n.

const message = `This is line 1
This is line 2
This is line 3`;

console.log(message);

Expression Evaluation

  • You can perform operations inside ${ }.

const a = 5, 
b = 10; 
console.log(`The sum of ${a} and ${b} is ${a + b}.`); 

// Output: The sum of 5 and 10 is 15.

Function Calls Inside Template Literals

function greet(name) { 
  return `Hello, ${name}!`; 
} 
console.log(`${greet("Himanshu")}`); 

// Output: Hello, Himanshu!

Tagged Template Literals (Advanced Feature)

  • You can use a function to process template literals.

function highlight(strings, ...values) { 
  return strings.reduce((result, str, i) => result + str + (values[i] ? values[i].toUpperCase() : ""), ""); 
} 

const name = "himanshu"; 
const lang = "javascript"; 

console.log(highlight`My name is ${name} and I love ${lang}.`); 

// Output: My name is HIMANSHU and I love JAVASCRIPT.

In short: Template literals let you create cleaner, more readable strings with variable interpolation, multi-line support, and even custom processing (tagged templates).

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *