Skip to main content
FREE Mock interview & resume review with Sumit. Free right now, no payment needed.Book a slot

JavaScript Spread and Rest Operators

Master the spread and rest operators for arrays and objects.

jiocoder TeamUpdated Jun 6, 20261 min readJavaScript
JavaScript Spread and Rest Operators

Spread Operator#

Arrays#

Code
// Copying arrays
const arr1 = [1, 2, 3];
const arr2 = [...arr1];

// Merging arrays
const merged = [...arr1, 4, 5, ...arr2];

// Adding elements
const newArr = [0, ...arr1, 4];

Objects#

Code
// Copying objects
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1 };

// Merging objects
const merged = { ...obj1, c: 3, d: 4 };

// Overriding properties
const updated = { ...obj1, b: 5 };

Rest Operator#

Code
// Function parameters
function sum(...numbers) {
  return numbers.reduce((acc, n) => acc + n, 0);
}

sum(1, 2, 3, 4); // 10

// Destructuring
const [first, ...rest] = [1, 2, 3, 4];
const { a, ...others } = { a: 1, b: 2, c: 3 };

Article discussion

(0)

Join the discussion — login to comment and help other developers.

Login to comment