Blog

ES6

JS

Spread vs Rest operator

A Swizz knife for JS devs

Ragav Kumar V

Ragav Kumar V

Aug 20, 2022 — Updated Aug 25, 2022 · 3 min read


_5
const a1 = [80, 40, 90];
_5
const a2 = [180, 240, 390];
_5
const a3 = [...a1, ...a2];
_5
_5
// a3 -> [80, 40, 90, 180, 240, 390 ]


_25
const avenger = {
_25
name: "Tony Stark",
_25
house: "🏘️",
_25
networth: "💰💰💰",
_25
power: "🤖",
_25
phrase: "❤️ you 3000",
_25
};
_25
_25
const details = {
_25
nation: "US",
_25
skill: ["genius", "billionaire", "playboy", "philanthropist"],
_25
};
_25
_25
const fullDetails = { ...avenger, ...details };
_25
_25
// fullDetails
_25
{
_25
name: "Tony Stark",
_25
house: "🏘️",
_25
networth: "💰💰💰",
_25
power: "🤖",
_25
phrase: "❤️ you 3000",
_25
nation: "US",
_25
skill: ["genius", "billionaire", "playboy", "philanthropist"],
_25
}


_20
const avenger = {
_20
name: "Tony Stark",
_20
house: "🏘️",
_20
networth: "💰💰💰",
_20
power: "🤖",
_20
phrase: "❤️ you 3000",
_20
};
_20
_20
const combine = { ...avenger, nation: "US", power: "💿" };
_20
_20
// combine - power is overridden - Whichever is last will overide the initial one
_20
_20
{
_20
name: "Tony Stark",
_20
house: "🏘️",
_20
networth: "💰💰💰",
_20
nation: "US",
_20
power: "💿",
_20
phrase: "❤️ you 3000",
_20
}


_8
const a1 = [80, 40, 90];
_8
const a2 = [...a1];
_8
const a3 = a1;
_8
_8
// a2 -> [80, 40, 90]
_8
// a3 -> [80, 40, 90]
_8
console.log(a1 === a2); // false
_8
console.log(a1 === a3); // true


_5
const a1 = [80, 40, 90];
_5
const a2 = [180, 240, 390];
_5
const a3 = [30, ...a1, 700, ...a2];
_5
_5
// a3 -> [30, 80, 40, 90, 700, 180, 240, 390]


_11
let nums = [4, 5, 20, 7];
_11
_11
console.log(Math.max(nums[0], nums[1], nums[2], nums[3])); // 20
_11
_11
console.log(Math.max(nums)); // NaN
_11
_11
// eg1: Spread
_11
console.log(Math.max(...nums)); // 20
_11
_11
// eg2: Spread
_11
console.log(Math.min(...nums)); // 4


_6
// eg: 1
_6
let [s1, ...s2] = ["eng", "maths", "social", "tamil"];
_6
console.log(s1, s2);
_6
_6
// s1 -> "eng"
_6
// s2 -> ["maths", "social", "tamil"]


_3
// eg: 2 - error - Rest element must be last element
_3
let [s1, ...s2, s3] = ["eng", "maths", "social", "tamil"];
_3
console.log(s1, s2, s3);


_10
function sum(...nums) {
_10
console.log(nums); // [4, 5, 7, 8, 9]
_10
let total = 0;
_10
for (let val of nums) {
_10
total = total + val;
_10
}
_10
return total;
_10
}
_10
_10
console.log(sum(4, 5, 7, 8, 9)); // 33

@ragavkumarv
swipe to next ➡️