JavaScript String Templates (Template Literals)
JavaScript में Template Strings या Template Literals एक powerful तरीका है strings को लिखने, जोड़ने और उनके अंदर variables या expressions embed करने का।
Template strings को backtick (`
) से लिखा जाता है और ${}
के ज़रिए हम उनके अंदर dynamic content जोड़ सकते हैं।
इस अध्याय में आप सीखेंगे:
- Template literals क्या हैं
- Variables को string में embed कैसे करें
- Multiline strings कैसे बनाएँ
- Expressions, function calls और nested templates
- अभ्यास प्रश्न
🔹 Template Literal क्या है?
Template literal एक special तरह की string है जिसे backtick (`
) से लिखा जाता है और जिसमें आप ${}
syntax के ज़रिए variables या expressions जोड़ सकते हैं।
Example:
let name = "Ravi";
let message = `Hello, ${name}!`;
console.log(message); // Output: Hello, Ravi!
🔹 Syntax
`Text before ${expression} text after`
जहां
expression
एक variable, calculation या function call हो सकता है।
🔹 Variable और Expression Embedding
Example 1: Variable
let firstName = "Neha";
let lastName = "Singh";
let fullName = `Your name is ${firstName} ${lastName}`;
console.log(fullName); // Output: Your name is Neha Singh
Example 2: Expression
let a = 10;
let b = 5;
let result = `Sum is ${a + b}`;
console.log(result); // Output: Sum is 15
🔹 Multiline Strings
Template literals से आप multi-line string को आसानी से लिख सकते हैं।
Example:
let poem = `Roses are red,
Violets are blue,
JavaScript is awesome,
And so are you.`;
console.log(poem);
/*
Output:
Roses are red,
Violets are blue,
JavaScript is awesome,
And so are you.
*/
🔹 Function Call Inside Template
function greet(name) {
return `Hello, ${name}`;
}
let message = `${greet("Amit")}, welcome!`;
console.log(message); // Output: Hello, Amit, welcome!
🔹 Nesting Template Literals
let user = "Riya";
let mood = "happy";
let msg = `User ${user} is feeling ${`${mood}`.toUpperCase()} today.`;
console.log(msg); // Output: User Riya is feeling HAPPY today.
🔹 Traditional String vs Template Literal
Feature | Traditional Strings | Template Literals |
---|---|---|
Syntax | “Hello” या ‘Hello’ | `Hello` |
Variable Injection | "Hello " + name | `Hello ${name}` |
Multiline Support | ❌ (नहीं सीधे) | ✅ |
Readability | Moderate | High |
अभ्यास प्रश्न
- Template string क्या होता है? इसे लिखने का syntax बताइए।
- नीचे दिए गए code का output क्या होगा?
let a = 5, b = 10; console.log(`The sum of ${a} and ${b} is ${a + b}`);
- Multiline string को traditional string और template literal दोनों तरीकों से लिखिए।
${}
के अंदर क्या-क्या लिखा जा सकता है?- कोई ऐसा example दीजिए जिसमें template literal के अंदर function call किया गया हो।