← Back to JavaScript Course | Chapter 5: ES6+ Features | Lesson 3 of 12

JS टेम्पलेट लिटरल्स

Template literals backticks से लिखी गई strings हैं जो आपको किसी वाक्य में सीधे values डालने देती हैं, जैसे कोई fill-in-the-blank। ये कई lines तक भी फैल सकती हैं।
Syntax
javascript
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

javascript
const name = "Sam";
console.log(`Hello, ${name}!`);

Expressions

${} के अंदर कोई भी valid JavaScript expression जा सकता है, एक साधारण variable से लेकर function call या arithmetic तक, और JavaScript उसे evaluate करके result को अपने आप एक स्ट्रिंग में बदल देता है।

उदाहरण: Expressions

javascript
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

javascript
// 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

javascript
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

javascript
const name = "Sam";
const age = 30;
console.log("Name: " + name + ", Age: " + age); // old way
console.log(`Name: ${name}, Age: ${age}`); // template literal
Live Example
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. backticks के बजाय single या double quotes इस्तेमाल करना, इसलिए "Hello ${name}" ${name} को literally print करता है।
  2. expression के चारों ओर ${} भूल जाना, जैसे ` Hello name , जो word name` print करता है।
  3. ${} के अंदर logic का एक complicated block रखना, जो string को पढ़ना मुश्किल बना देता है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.