- JS Introduction
- JS Introduction
- JS Comments
- JS Variables
- JS Datatypes
- JS Operators
- JS Type Conversions
- JS Control Flow
- JS Comparisons
- JS If else
- JS If else Ladder
- JS Ternary Operator
- JS Switch
- JS For Loop
- JS For In
- JS For Of
- JS While
- JS Do While
- JS Break & Continue
- JS Functions
- JS Function Declaration
- JS Function Parameters
- JS Return Statement
- JS Function Expressions
- JS Anonymous Functions
- JS Objects
- JS Objects
- JS Object Methods
- JS Object Constructors
- JS Object Destructuring
- JS Object Prototypes
- JS Map, Filter & Reduce
- JS ES6
- JS ES6
- JS let and const
- JS Arrow Functions
- JS Template Literals
- Destructuring Assignment
- JS Spread Operator
- JS Default Parameters
- JS Classes
- JS Inheritance
- JS Map
- JS Set
- JS Async
- JS Callbacks
- JS Asynchronous
- JS Promises
- JS Async/Await
- JS HTML DOM/BOM
- JS Document Object
- JS getElementbyId
- getElementsByClassName
- JS getElementsByName
- getElementsByTagName
- JS innerHTML
- JS outerHTML
- JS Window Object
- JS History Object
- JS Navigator Object
- JS Screen Object
JavaScript Template Literals
Template literals are a powerful feature introduced in ES6 (ECMAScript 2015) that revolutionized how we handle strings in JavaScript. Before template literals, developers had to rely on single or double quotes, which made complex string manipulation and multi-line text quite cumbersome. Template literals use backticks (`) instead of quotes, unlocking a much more flexible syntax.
String Interpolation:
- Template literals allow you to embed variables and expressions directly within strings using the ${expression} syntax.
- This provides a much cleaner, more readable, and concise alternative to traditional string concatenation using the
+operator.
Multi-line Strings:
- With standard strings, creating a new line requires the escape character \n. Template literals support multi-line strings natively—whatever you type inside the backticks, including line breaks and spaces, is preserved exactly as written.
Expression Evaluation:
- Anything placed inside the ${} placeholders is evaluated as standard JavaScript. This means you can perform math, call functions, or even use ternary operators right inside your string.
{variable} instead of ${variable}. Without the $, JavaScript treats it as a literal part of the string rather than an expression.
Example: Basic Usage
In this example, see how much cleaner it is to inject the name variable directly into the greeting compared to using 'Hello, ' + name + '!'.
const name = 'John';
const message = `Hello, ${name}!`;
console.log(message); // Output: Hello, John!
Example: Multi-line Strings
Template literals are perfect for creating blocks of text or even generating HTML snippets directly in your script.
const emailBody = `Dear Customer,
Thank you for your recent order.
Your items will ship within 24 hours.
Best regards,
Support Team`;
console.log(emailBody);
Example: Expression Evaluation
You can perform logic on the fly. This reduces the need for "helper" variables that only exist to hold a calculated value for a string.
const itemPrice = 49.99;
const taxRate = 0.08;
// Calculating the total price directly inside the string
const receipt = `Total: $${(itemPrice * (1 + taxRate)).toFixed(2)}`;
console.log(receipt); // Output: Total: $53.99
Practical Real-World Example: Building HTML
One of the most common uses for template literals is dynamically generating UI components in vanilla JavaScript.
const user = {
id: 101,
username: 'dev_pro',
role: 'Admin'
};
const userCard = `
${user.username}
Status: ${user.role === 'Admin' ? 'System Access Granted' : 'Standard User'}
`;
${}, keep it readable. If an expression gets too long or complex, calculate the value in a variable first and then pass that variable into the template literal.
Key Points
- Readability: Template literals eliminate the "quote soup" caused by multiple
+signs and closing/opening quotes. - Flexibility: They allow for easy integration of dynamic data, logic, and multi-line formatting in a single block.
- Standard Practice: In modern JavaScript (React, Vue, Node.js), template literals are the industry standard for string generation and URL construction.
- Security Note: When using template literals to insert user-generated content into the HTML DOM, always sanitize the input to prevent Cross-Site Scripting (XSS) attacks.