What are template literals and what advantages do they offer over regular strings? Template literals क्या हैं और regular strings पर क्या फायदे देते हैं?
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>!'| Feature | Regular strings | Template literals |
|---|---|---|
| Interpolation | String + concatenation | ${expression} |
| Multi-line | \n escape sequence | Native support |
| Readability | Hard to read long strings | Very readable |
| Tagged templates | Not possible | Supported |
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}!`;| Feature | Regular strings | Template literals |
|---|---|---|
| Interpolation | String + concatenation | ${expression} |
| Multi-line | \n escape sequence | Native support |
| Readability | कठिन | बहुत clear |
| Tagged templates | नहीं | हाँ |
इंटरव्यू टिप: बताएं template literals code को ज़्यादा readable और कम error-prone बनाते हैं। Tagged templates का advanced use cases के लिए ज़िक्र करें।
Was this answer clear?