The three-dot syntax (...) was introduced in ES6 and serves two completely opposite, complementary roles depending on context: Spread (expands elements out) and Rest (gathers elements together).
const frontend = ["HTML", "CSS", "JavaScript"];
const backend = ["Node.js", "PHP", "Python"];
// Merging without concat():
const fullStack = [...frontend, ...backend, "Linux"];
console.log(fullStack); // ["HTML", "CSS", "JavaScript", "Node.js", "PHP", "Python", "Linux"]
// Shallow Cloning:
const clonedArray = [...frontend];
clonedArray.push("TypeScript");
console.log(frontend.length); // 3 (Original remains untainted!)
const userPreferences = { theme: "dark", notifications: true };
const userProfile = { name: "Vikram", email: "v@v.com" };
// Merge into single object with overrides:
const fullUser = { ...userProfile, ...userPreferences, status: "Active" };
console.log(fullUser);
// A. Rest in Array Destructuring
const [firstRank, secondRank, ...runnerUps] = ["Aarav", "Diya", "Kabir", "Meera", "Rohan"];
console.log("Champion:", firstRank); // "Aarav"
console.log("Runner-Ups:", runnerUps); // ["Kabir", "Meera", "Rohan"]
// B. Rest in Object Destructuring (Clean extraction)
const { password, ...safeUser } = { id: 101, username: "admin", password: "SecretPassword123" };
console.log(safeUser); // { id: 101, username: "admin" } (Sensitive data stripped!)
Exam Question: "How do you pass an array of numbers to Math.max() using the spread operator?"
const numbers = [12, 45, 98, 23, 67];
// Math.max expects individual arguments, NOT an array:
// Math.max(numbers) -> Returns NaN!
// SOLUTION: Spread expands array elements as individual arguments:
const maxVal = Math.max(...numbers);
console.log("Maximum:", maxVal); // 98
What specialized ES6 collections handle arbitrary key types and unique sets? Proceed to: JavaScript Map, Set, WeakMap & WeakSet →