Spread vs Rest operator
Spread operator ...
i. Concat or Merge arrays
_5const a1 = [80, 40, 90];_5const a2 = [180, 240, 390];_5const a3 = [...a1, ...a2];_5_5// a3 -> [80, 40, 90, 180, 240, 390 ]
ii. Concat or Merge objects
_25const avenger = {_25 name: "Tony Stark",_25 house: "🏘️",_25 networth: "💰💰💰",_25 power: "🤖",_25 phrase: "❤️ you 3000",_25};_25_25const details = {_25 nation: "US",_25 skill: ["genius", "billionaire", "playboy", "philanthropist"],_25};_25_25const 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}
iii. Override keys in objects
_20const avenger = {_20 name: "Tony Stark",_20 house: "🏘️",_20 networth: "💰💰💰",_20 power: "🤖",_20 phrase: "❤️ you 3000",_20};_20_20const 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}
iv. Copy arrays & objects
_8const a1 = [80, 40, 90];_8const a2 = [...a1];_8const a3 = a1;_8_8// a2 -> [80, 40, 90]_8// a3 -> [80, 40, 90]_8console.log(a1 === a2); // false_8console.log(a1 === a3); // true
v. Spread used in any position in the array
_5const a1 = [80, 40, 90];_5const a2 = [180, 240, 390];_5const a3 = [30, ...a1, 700, ...a2];_5_5// a3 -> [30, 80, 40, 90, 700, 180, 240, 390]
vi. To pass array as separate arguments
_11let nums = [4, 5, 20, 7];_11_11console.log(Math.max(nums[0], nums[1], nums[2], nums[3])); // 20_11_11console.log(Math.max(nums)); // NaN_11_11// eg1: Spread_11console.log(Math.max(...nums)); // 20_11_11// eg2: Spread_11console.log(Math.min(...nums)); // 4
Rest operator ...
i. Destructing - Collecting rest of the values
_6// eg: 1_6let [s1, ...s2] = ["eng", "maths", "social", "tamil"];_6console.log(s1, s2);_6_6// s1 -> "eng"_6// s2 -> ["maths", "social", "tamil"]
ii. Rest element must be last element
_3// eg: 2 - error - Rest element must be last element_3let [s1, ...s2, s3] = ["eng", "maths", "social", "tamil"];_3console.log(s1, s2, s3);
iii. Collecting multiple arguments in function
_10function 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_10console.log(sum(4, 5, 7, 8, 9)); // 33
@ragavkumarv
swipe to next ➡️