JS Template Literals
In this page:
const text = `text ${expression} more text`;
const multiLine = `line one
line two`;
Basic Template Literals
Template literals are strings wrapped in backticks ` instead of quotes, and they let you embed variables and expressions directly inside the string using ${} syntax.
उदाहरण: Basic Template Literals
const name = "Sam";
console.log(`Hello, ${name}!`);
Expressions
Any valid JavaScript expression can go inside ${}, from a simple variable to a function call or arithmetic, and JavaScript evaluates it and converts the result to a string automatically.
उदाहरण: Expressions
const a = 2, b = 3;
console.log(`Sum: ${a + b}`);
Multiline Strings
Unlike regular strings, template literals can span multiple lines just by pressing enter inside the backticks, without needing explicit \n characters or string concatenation.
उदाहरण: Multiline Strings
// Declare the constant `message`, set to ``Line one`
const message = `Line one
Line two`;
// Print `message` to the console
console.log(message);
Nested Templates
Template literals can be nested inside each other's ${} expressions, which is useful for conditional formatting, like showing a different piece of text depending on a value.
उदाहरण: Nested Templates
const isAdmin = true;
console.log(`Role: ${isAdmin ? `Admin ${1}` : "User"}`);
Template Literal Benefits
Template literals remove the need for messy string concatenation with +, making code that mixes text and variables noticeably easier to read and less error-prone, especially once more than one or two variables are involved.
उदाहरण: Template Literal Benefits
const name = "Sam";
const age = 30;
console.log("Name: " + name + ", Age: " + age); // old way
console.log(`Name: ${name}, Age: ${age}`); // template literal
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: