JS Rest and Spread Operator

The Rest (...) and Spread (...) operators both use three dots (...) but serve different purposes based on their context.

Rest Operator (...)

The Rest Operator is used to collect remaining arguments into an array.

It is primarily used in function parameters.

Example
const [...arr] = [1, 2, 3, 4, 5];
const [first, second, ...rest] = [1, 2, 3, 4, 5];
console.log(arr); // [1, 2, 3, 4, 5]
console.log(first); // 1
console.log(second); // 2
console.log(rest); // [3, 4, 5]

// function
function sum(...numbers) {
return numbers;
}
console.log(sum(1, 2, 3, 4)); // Output: [1,2,3,4]

Try it yourself


Spread Operator (...)

The Spread Operator is used to expand iterable elements (like arrays or objects) into individual elements.

Example
const array = [1, 2, 3];
console.log(...array);

// array
const numbers = [1, 2, 3];
const moreNumbers = [...numbers, 4, 5];
console.log(moreNumbers); // [1, 2, 3, 4, 5]

// Object
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };
console.log(obj2); // { a: 1, b: 2, c: 3 }

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.