JS टेम्पलेट लिटरल्स
In this page:
const text = `text ${expression} more text`;
const multiLine = `line one
line two`;
Basic Template Literals
Template literals quotes के बजाय backticks ` में लपेटी गई strings हैं, और ये आपको ${} syntax का इस्तेमाल करके variables और expressions सीधे स्ट्रिंग के अंदर embed करने देती हैं।
उदाहरण: Basic Template Literals
const name = "Sam";
console.log(`Hello, ${name}!`);
Expressions
${} के अंदर कोई भी valid JavaScript expression जा सकता है, एक साधारण variable से लेकर function call या arithmetic तक, और JavaScript उसे evaluate करके result को अपने आप एक स्ट्रिंग में बदल देता है।
उदाहरण: Expressions
const a = 2, b = 3;
console.log(`Sum: ${a + b}`);
Multiline Strings
regular strings के उलट, template literals सिर्फ backticks के अंदर enter दबाकर कई lines तक फैल सकते हैं, बिना explicit \n characters या 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 एक-दूसरे के ${} expressions के अंदर nest किए जा सकते हैं, जो conditional formatting के लिए उपयोगी है, जैसे किसी value के हिसाब से अलग text दिखाना।
उदाहरण: Nested Templates
const isAdmin = true;
console.log(`Role: ${isAdmin ? `Admin ${1}` : "User"}`);
Template Literal के फायदे
Template literals + से गड़बड़ string concatenation करने की ज़रूरत हटा देते हैं, जिससे text और variables को मिलाने वाला code काफी आसानी से पढ़ने लायक और कम error-prone बन जाता है, खासतौर पर जब एक या दो से ज़्यादा variables शामिल हों।
उदाहरण: 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
- backticks के बजाय single या double quotes इस्तेमाल करना, इसलिए
"Hello ${name}"${name}को literally print करता है। - expression के चारों ओर
${}भूल जाना, जैसे `Hello name, जो wordname` print करता है। ${}के अंदर logic का एक complicated block रखना, जो string को पढ़ना मुश्किल बना देता है।
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: