📘 Lesson · Lesson 41
Template Literals
Template Literals
Backticks and Interpolation
const name = "Aman";
const marks = 85;
// The old way — a mess of + signs and quotes:
const msg1 = "Student " + name + " scored " + marks + " marks.";
// Template literal — backticks and ${ }:
const msg2 = `Student ${name} scored ${marks} marks.`;
Template literals use backticks
` instead of quotes, and let you insert variables directly with ${...}. You met these back in the strings chapter, and they're worth revisiting because they've become the default way to build strings in modern JavaScript. Compare the two lines above: the template version has no + juggling, no accidentally-missing spaces, and reads almost like the sentence it produces. The backtick key sits above Tab on most keyboards, to the left of the 1 key.Any Expression Fits Inside ${ }
const price = 100, qty = 3;
`Total: ₹${price * qty}` // "Total: ₹300" — maths
`Name: ${name.toUpperCase()}` // method calls work
`Status: ${marks >= 33 ? "Pass" : "Fail"}` // a ternary!
`Items: ${items.length}` // property access
`Sum: ${nums.reduce((a, b) => a + b, 0)}` // even a whole function call
Inside
${ } you can place any JavaScript EXPRESSION — anything that produces a value. That includes arithmetic, method calls, property lookups, ternaries, and function calls. This is far more powerful than simple variable substitution. The ternary trick is especially common: ${isLoggedIn ? "Logout" : "Login"} lets you choose text inline. What you CANNOT put inside is a statement — no if blocks, no for loops. If you need those, compute the value first, then insert it.Multi-line Strings — no more \n
// The old way — awkward escapes and concatenation:
const old = "Line one\n" +
"Line two\n" +
"Line three";
// Template literal — just press Enter:
const modern = `Line one
Line two
Line three`;
A template literal preserves line breaks exactly as you type them — no
\n escapes, no string concatenation across lines. Whatever whitespace and indentation you write is kept in the output, which is both convenient and a small trap: indenting your template to match your code's indentation adds those spaces to the string. For plain text output this rarely matters; for HTML it never matters, since browsers collapse whitespace anyway.Building HTML — the killer use case
const student = { name: "Aman", marks: 85, city: "Aligarh" };
const card = `
${student.name}
Marks: ${student.marks}
${student.marks >= 33 ? "Passed" : "Failed"}
`;
document.querySelector("#container").innerHTML = card;
// Even better — build a whole list with map + join:
const students = [{name:"Aman"}, {name:"Priya"}];
const html = students.map(s => `${s.name} `).join("");
Combining template literals with
map() and join("") is THE standard way to render a list of data as HTML. map turns each object into an HTML string, and join("") glues them into one big string ready for innerHTML. Notice you can even put a ternary inside a class attribute to switch styling conditionally. Multi-line templates keep the HTML readable and properly indented — try building this with + concatenation and you'll appreciate the difference immediately.Safety — remember the innerHTML warning
// ✗ DANGEROUS — user content inside innerHTML
const comment = getUserComment(); // could contain <script>...
container.innerHTML = `${comment}
`; // XSS vulnerability!
// ✓ SAFE — use textContent for user-supplied data
const p = document.createElement("p");
p.textContent = comment; // tags are shown as text, not run
container.appendChild(p);
Template literals make it very easy to build HTML strings — which makes it very easy to introduce an XSS vulnerability. If any part of your template comes from a user (a comment, a username, a search term), inserting it via
innerHTML lets them inject scripts. The rule from the DOM chapter still stands: use templates + innerHTML for content YOU control; use textContent or createElement for anything a user typed. Template literals are a formatting tool, not a security boundary.Exam Corner
Q: What character wraps a template literal? The backtick
Q: How do you insert a variable? With
Q: Can you put a ternary inside ${ }? Yes — any expression works, but not statements like if or for.
Q: How do you write a multi-line string? Just press Enter inside the backticks — line breaks are preserved.
Q: How do you render an array of objects as HTML?
`.Q: How do you insert a variable? With
${variableName}.Q: Can you put a ternary inside ${ }? Yes — any expression works, but not statements like if or for.
Q: How do you write a multi-line string? Just press Enter inside the backticks — line breaks are preserved.
Q: How do you render an array of objects as HTML?
arr.map(o => `<li>${o.name}</li>`).join("")
Backticks और Interpolation
const name = "Aman";
const marks = 85;
// Purana tarika — + signs aur quotes ki gandagi:
const msg1 = "Student " + name + " scored " + marks + " marks.";
// Template literal — backticks aur ${ }:
const msg2 = `Student ${name} scored ${marks} marks.`;
Template literals quotes के बजाय backticks
` use करते हैं, और आपको ${...} से सीधे variables डालने देते हैं. आप इन्हें strings chapter में मिल चुके, और दोबारा देखने लायक हैं क्योंकि वे modern JavaScript में strings बनाने का default तरीका बन चुके हैं. ऊपर की दोनों lines तुलना कीजिए: template version में कोई + जुगलबंदी नहीं, कोई गलती से गायब spaces नहीं, और यह लगभग उसी वाक्य जैसा पढ़ता है जो बनाता है. Backtick key ज़्यादातर keyboards पर Tab के ऊपर, 1 key के बाईं ओर होती है.${ } के अंदर कोई भी Expression
const price = 100, qty = 3;
`Total: ₹${price * qty}` // "Total: ₹300" — ganit
`Name: ${name.toUpperCase()}` // method calls chalte hain
`Status: ${marks >= 33 ? "Pass" : "Fail"}` // ternary!
`Items: ${items.length}` // property access
`Sum: ${nums.reduce((a, b) => a + b, 0)}` // poora function call bhi
${ } के अंदर आप कोई भी JavaScript EXPRESSION रख सकते हैं — जो कुछ भी value बनाए. इसमें arithmetic, method calls, property lookups, ternaries, और function calls शामिल हैं. यह सरल variable substitution से कहीं ज़्यादा ताकतवर है. Ternary trick खासकर common है: ${isLoggedIn ? "Logout" : "Login"} आपको inline text चुनने देता है. जो आप अंदर NAHI रख सकते वह statement है — कोई if blocks नहीं, कोई for loops नहीं. वे चाहिए तो पहले value निकालिए, फिर डालिए.Multi-line Strings — अब \n नहीं
// Purana tarika — bhadde escapes aur concatenation:
const old = "Line one\n" +
"Line two\n" +
"Line three";
// Template literal — bas Enter dabaiye:
const modern = `Line one
Line two
Line three`;
Template literal line breaks को ठीक वैसे रखता है जैसे आप type करते हैं — कोई
\n escapes नहीं, lines में string concatenation नहीं. आप जो भी whitespace और indentation लिखें वह output में रहता है, जो सुविधाजनक और छोटा जाल दोनों है: अपने template को code के indentation से match करने को indent करना वे spaces string में जोड़ देता है. सादे text output के लिए यह शायद ही मायने रखता है; HTML के लिए कभी नहीं, चूंकि browsers वैसे भी whitespace समेट देते हैं.HTML बनाना — killer use case
const student = { name: "Aman", marks: 85, city: "Aligarh" };
const card = `
${student.name}
Marks: ${student.marks}
${student.marks >= 33 ? "Passed" : "Failed"}
`;
document.querySelector("#container").innerHTML = card;
// Aur behtar — map + join se poori list banaiye:
const students = [{name:"Aman"}, {name:"Priya"}];
const html = students.map(s => `${s.name} `).join("");
Template literals को
map() और join("") के साथ मिलाना data की list को HTML के रूप में render करने का STANDARD तरीका है. map हर object को HTML string में बदलता है, और join("") उन्हें innerHTML के लिए तैयार एक बड़ी string में चिपकाता है. ध्यान दीजिए आप class attribute के अंदर ternary रखकर styling conditionally बदल सकते हैं. Multi-line templates HTML को readable और ठीक से indented रखते हैं — इसे + concatenation से बनाकर देखिए और आप फर्क तुरंत सराहेंगे.Safety — innerHTML चेतावनी याद रखिए
// ✗ KHATRNAK — innerHTML ke andar user content
const comment = getUserComment(); // isme <script> ho sakta hai...
container.innerHTML = `${comment}
`; // XSS vulnerability!
// ✓ SURAKSHIT — user ke diye data ke liye textContent
const p = document.createElement("p");
p.textContent = comment; // tags text dikhte hain, chalte nahi
container.appendChild(p);
Template literals HTML strings बनाना बहुत आसान बनाते हैं — जो XSS vulnerability डालना भी बहुत आसान बनाता है. अगर आपके template का कोई हिस्सा user से आए (comment, username, search term), उसे
innerHTML से डालना उन्हें scripts inject करने देता है. DOM chapter का नियम अब भी खड़ा है: अपने NIYANTRIT content के लिए templates + innerHTML use कीजिए; user के type किए किसी भी चीज़ के लिए textContent या createElement. Template literals formatting tool हैं, security सीमा नहीं.Exam Corner
Q: Template literal को कौन-सा character लपेटता है? Backtick
Q: Variable कैसे डालते हैं?
Q: क्या ${ } के अंदर ternary रख सकते हैं? हां — कोई भी expression चलता है, पर if या for जैसे statements नहीं.
Q: Multi-line string कैसे लिखते हैं? Backticks के अंदर बस Enter दबाइए — line breaks सुरक्षित रहते हैं.
Q: Objects की array को HTML के रूप में कैसे render करते हैं?
`.Q: Variable कैसे डालते हैं?
${variableName} से.Q: क्या ${ } के अंदर ternary रख सकते हैं? हां — कोई भी expression चलता है, पर if या for जैसे statements नहीं.
Q: Multi-line string कैसे लिखते हैं? Backticks के अंदर बस Enter दबाइए — line breaks सुरक्षित रहते हैं.
Q: Objects की array को HTML के रूप में कैसे render करते हैं?
arr.map(o => `<li>${o.name}</li>`).join("")
💻 Live Code Editor
इस पेज का code यहाँ तैयार है — बदलिए और तुरंत नतीजा देखिए. कुछ install किए बिना.
सब कुछ आपके browser में ही चलता है — कोई server, कोई signup नहीं. JavaScript का
console.log देखने के लिए F12 दबाइए.