Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 9 of 10 · JavaScript Basics & Fundamentals
Interview question

What are template literals and what advantages do they offer over regular strings? Template literals क्या हैं और regular strings पर क्या फायदे देते हैं?

Answer

Template literals (backticks) allow string interpolation, multi-line strings, and expression evaluation - cleaner than string concatenation.

// Regular strings
const name = 'John';
const greeting = 'Hello, ' + name + '!'; // Concatenation
const multiline = 'Line 1\nLine 2'; // Need \n
// Template literals
const greeting2 = `Hello, ${name}!`; // Interpolation
const multiline2 = `Line 1
Line 2`; // Native multi-line
const expr = `5 + 3 = ${5 + 3}`; // Expression evaluation

// Tagged template literals
function highlight(strings, ...values) {
    return strings.map((str, i) => str + (values[i] ? '<mark>' + values[i] + '</mark>' : '')).join('');
}
const html = highlight`Hello ${name}!`;
// 'Hello <mark>John</mark>!'
FeatureRegular stringsTemplate literals
InterpolationString + concatenation${expression}
Multi-line\n escape sequenceNative support
ReadabilityHard to read long stringsVery readable
Tagged templatesNot possibleSupported

Interview tip: Mention that template literals make code more readable and less error-prone. Also mention tagged templates for advanced use cases like formatting, escaping, or localization.

Template literals (backticks) string interpolation, multi-line strings, और expression evaluation allow करते हैं - string concatenation से ज़्यादा clean।

const name = 'John';

// Regular strings
const greeting = 'Hello, ' + name + '!'; // Concatenation
const multiline = 'Line 1\nLine 2';

// Template literals
const greeting2 = `Hello, ${name}!`; // Interpolation
const multiline2 = `Line 1
Line 2`; // Multi-line
const expr = `5 + 3 = ${5 + 3}`; // Expression

// Tagged template literals
function highlight(strings, ...values) {
    return strings.map((str, i) => str + (values[i] ? '<mark>' + values[i] + '</mark>' : '')).join('');
}
const html = highlight`Hello ${name}!`;
FeatureRegular stringsTemplate literals
InterpolationString + concatenation${expression}
Multi-line\n escape sequenceNative support
Readabilityकठिनबहुत clear
Tagged templatesनहींहाँ

इंटरव्यू टिप: बताएं template literals code को ज़्यादा readable और कम error-prone बनाते हैं। Tagged templates का advanced use cases के लिए ज़िक्र करें।

Was this answer clear?