Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
In JavaScript operators spread and rest use the ... syntax, but their purpose depends on the context in which they're used.
Spread is used for:
const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4, 5]; // [1, 2, 3, 4, 5]
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const combined = { ...obj1, ...obj2 }; // { a: 1, b: 2, c: 3, d: 4 }
function sum(a, b, c) {
return a + b + c;
}
const values = [1, 2, 3];
console.log(sum(...values)); // 6
Rest is used for:
function multiply(multiplier, ...numbers) {
return numbers.map(num => num * multiplier);
}
console.log(multiply(2, 1, 2, 3)); // [2, 4, 6]
const [first, second, ...others] = [1, 2, 3, 4, 5];
console.log(first); // 1
console.log(second); // 2
console.log(others); // [3, 4, 5]
const { a, b, ...restProps } = { a: 10, b: 20, c: 30, d: 40 };
console.log(a); // 10
console.log(b); // 20
console.log(restProps); // { c: 30, d: 40 }
Both operators use ..., but:
These operators make code more flexible, concise and clear, helping efficiently manage data collections in JavaScript.