Template Literals & Destructuring
📖 Concept
Template Literals (backticks \``) allow embedded expressions, multi-line strings, and tagged templates.
Destructuring extracts values from arrays or properties from objects into distinct variables. It's like unpacking a suitcase — you take out exactly what you need.
Array destructuring uses position: const [a, b] = [1, 2]
Object destructuring uses property names: const { name, age } = person
Both support defaults, renaming, nested destructuring, and rest patterns.
🏠 Real-world analogy: Destructuring is like opening a gift box and immediately labeling each item. Instead of reaching into the box every time, you lay everything out and name it.
💻 Code Example
1// Template literals2const name = "Alice";3const age = 25;45// String interpolation6const greeting = `Hello, ${name}! You are ${age} years old.`;78// Multi-line strings9const html = `10 <div>11 <h1>${name}</h1>12 <p>Age: ${age}</p>13 </div>14`;1516// Expressions in templates17console.log(`Total: $${(19.99 * 3).toFixed(2)}`); // "Total: $59.97"18console.log(`Status: ${age >= 18 ? 'Adult' : 'Minor'}`);1920// Tagged templates21function highlight(strings, ...values) {22 return strings.reduce((result, str, i) => {23 return result + str + (values[i] ? `<mark>${values[i]}</mark>` : "");24 }, "");25}26const msg = highlight`Hello ${name}, you are ${age}`;2728// Array destructuring29const [first, second, ...rest] = [1, 2, 3, 4, 5];30console.log(first, second, rest); // 1, 2, [3, 4, 5]3132// Skip elements33const [, , third] = [1, 2, 3]; // third = 33435// Swap variables36let a = 1, b = 2;37[a, b] = [b, a]; // a=2, b=13839// Object destructuring40const user = { name: "Bob", age: 30, city: "NYC", country: "US" };41const { name: userName, age: userAge, role = "user" } = user;42// Renamed + default value4344// Nested destructuring45const config = {46 server: { host: "localhost", port: 3000 },47 db: { name: "mydb" }48};49const { server: { host, port }, db: { name: dbName } } = config;5051// Function parameter destructuring52function createUser({ name, age, role = "member" }) {53 return `${name} (${role}), age ${age}`;54}55createUser({ name: "Charlie", age: 28 });
🏋️ Practice Exercise
Mini Exercise:
- Use destructuring to swap two variables without a temp variable
- Write a function that takes an object parameter and destructures it with defaults
- Use nested destructuring to extract deeply nested API response data
- Create a tagged template literal that escapes HTML characters
⚠️ Common Mistakes
Forgetting to wrap object destructuring in an assignment with parentheses:
({ a, b } = obj)— without(),{is treated as a blockDestructuring
nullorundefinedthrows — always provide a default:const { a } = obj || {}Order matters for array destructuring but NOT for object destructuring
Forgetting the alias syntax:
{ name: localName }means 'extractnameand call itlocalName', NOT 'extractlocalName'Overusing deep destructuring makes code harder to read — balance convenience with clarity
💼 Interview Questions
🎤 Mock Interview
Mock interview is powered by AI for Template Literals & Destructuring. Login to unlock this feature.