JavaScript Spread and Rest Operators: Shallow Cloning, Merging & Rest Args

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

1. The Spread Operator (Expanding & Cloning)

A. Merging & Cloning Arrays

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!)

B. Merging Objects

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);

2. The Rest Operator (Gathering Remaining Elements)

// 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!)

University Exam Corner (BCA Examination Notes)

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

Next Step

What specialized ES6 collections handle arbitrary key types and unique sets? Proceed to: JavaScript Map, Set, WeakMap & WeakSet →

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!