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

codeTap to expand ⛶
1// Template literals
2const name = "Alice";
3const age = 25;
4
5// String interpolation
6const greeting = `Hello, ${name}! You are ${age} years old.`;
7
8// Multi-line strings
9const html = `
10 <div>
11 <h1>${name}</h1>
12 <p>Age: ${age}</p>
13 </div>
14`;
15
16// Expressions in templates
17console.log(`Total: $${(19.99 * 3).toFixed(2)}`); // "Total: $59.97"
18console.log(`Status: ${age >= 18 ? 'Adult' : 'Minor'}`);
19
20// Tagged templates
21function 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}`;
27
28// Array destructuring
29const [first, second, ...rest] = [1, 2, 3, 4, 5];
30console.log(first, second, rest); // 1, 2, [3, 4, 5]
31
32// Skip elements
33const [, , third] = [1, 2, 3]; // third = 3
34
35// Swap variables
36let a = 1, b = 2;
37[a, b] = [b, a]; // a=2, b=1
38
39// Object destructuring
40const user = { name: "Bob", age: 30, city: "NYC", country: "US" };
41const { name: userName, age: userAge, role = "user" } = user;
42// Renamed + default value
43
44// Nested destructuring
45const config = {
46 server: { host: "localhost", port: 3000 },
47 db: { name: "mydb" }
48};
49const { server: { host, port }, db: { name: dbName } } = config;
50
51// Function parameter destructuring
52function createUser({ name, age, role = "member" }) {
53 return `${name} (${role}), age ${age}`;
54}
55createUser({ name: "Charlie", age: 28 });

🏋️ Practice Exercise

Mini Exercise:

  1. Use destructuring to swap two variables without a temp variable
  2. Write a function that takes an object parameter and destructures it with defaults
  3. Use nested destructuring to extract deeply nested API response data
  4. 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 block

  • Destructuring null or undefined throws — always provide a default: const { a } = obj || {}

  • Order matters for array destructuring but NOT for object destructuring

  • Forgetting the alias syntax: { name: localName } means 'extract name and call it localName', NOT 'extract localName'

  • 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.