What are template literals and why are they better than string concatenation?
Template literals use backticks. They allow ${expression} interpolation and multi-line strings without escape characters, which makes strings with variables far easier to read than chains of + signs.
Explain it simply
Compare a WhatsApp forward template, "Hi NAME, your fee is AMOUNT", with and without blanks. Backticks let you leave a blank ${...} right inside the text and JavaScript fills it with the value of any expression: a variable, a calculation, a function call or a ternary.
Benefits over +:
- Readable: no quotes closing and reopening around every variable.
- Multi-line: line breaks inside backticks are kept as they are.
- Safe with numbers: no surprise
"5" + 3concatenation confusion.
There are also tagged templates, where a function processes the pieces; libraries like styled-components use them.
Example
const name = "Asha";
const fee = 500;
console.log("Hi " + name + ", pay " + fee * 2); // Output: Hi Asha, pay 1000
console.log(`Hi ${name}, pay ₹${fee * 2}`); // Output: Hi Asha, pay ₹1000
console.log(`Level: ${fee > 400 ? "high" : "low"}`); // Output: Level: high
const note = `line one
line two`; // the line break is kept
console.log(note.split("\n").length); // Output: 2What to say in the interview
"Template literals use backticks and ${} to embed any expression, and they preserve newlines. They are clearer and less error-prone than concatenation. I also know tagged templates exist for custom processing, like escaping HTML."
Common mistakes
- Using single quotes with ${}. Interpolation only works inside backticks.
- Putting untrusted user input straight into HTML templates, which opens the door to XSS.