Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 3 of 10 · ES6+ Features
Interview question

How do template literals improve string handling in JavaScript? Template literals JavaScript में string handling को कैसे बेहतर बनाते हैं?

Answer

Template literals use backticks instead of quotes, enabling embedded expressions, multi-line strings, and tagged templates without messy concatenation.

// Old way - string concatenation
const name = 'John';
const age = 30;
const oldWay = 'My name is ' + name + ' and I am ' + age + ' years old.';

// Template literals - interpolation
const newWay = `My name is ${name} and I am ${age} years old.`;
console.log(newWay);

// Expressions inside ${}
const a = 5, b = 10;
console.log(`Sum is ${a + b}`); // Sum is 15
console.log(`${a > b ? 'a is bigger' : 'b is bigger'}`); // b is bigger

// Multi-line strings without \n concatenation
const multiLine = `Line 1
Line 2
Line 3`;
console.log(multiLine);

// Function calls inside template literals
function formatCurrency(amount) {
    return `$${amount.toFixed(2)}`;
}
const price = 19.5;
console.log(`Total: ${formatCurrency(price)}`); // Total: $19.50

// Nested template literals
const isVIP = true;
const message = `Welcome ${isVIP ? `VIP ${name}` : name}!`;

// Tagged templates - custom processing of template strings
function highlight(strings, ...values) {
    return strings.reduce((result, str, i) => {
        return `${result}${str}${values[i] ? `<mark>${values[i]}</mark>` : ''}`;
    }, '');
}
const product = 'Laptop', discount = '20%';
console.log(highlight`Buy ${product} and get ${discount} off!`);
// Buy <mark>Laptop</mark> and get <mark>20%</mark> off!

Template literals quotes की बजाय backticks use करते हैं, embedded expressions, multi-line strings, और tagged templates बिना messy concatenation के देते हैं।

// पुराना तरीका - concatenation
const name = 'John';
const age = 30;
const oldWay = 'My name is ' + name + ' and I am ' + age + ' years old.';

// Template literals
const newWay = `My name is ${name} and I am ${age} years old.`;

// Expressions ${} के अंदर
const a = 5, b = 10;
console.log(`Sum is ${a + b}`); // Sum is 15

// Multi-line strings
const multiLine = `Line 1
Line 2
Line 3`;

// Function calls अंदर
function formatCurrency(amount) {
    return `$${amount.toFixed(2)}`;
}
console.log(`Total: ${formatCurrency(19.5)}`); // Total: $19.50

// Tagged templates
function highlight(strings, ...values) {
    return strings.reduce((result, str, i) => {
        return `${result}${str}${values[i] ? `<mark>${values[i]}</mark>` : ''}`;
    }, '');
}
console.log(highlight`Buy ${'Laptop'} today!`);

Was this answer clear?