Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save KeyurRamoliya/8a5c6a08a1caef7a33627a0880341979 to your computer and use it in GitHub Desktop.
Save KeyurRamoliya/8a5c6a08a1caef7a33627a0880341979 to your computer and use it in GitHub Desktop.
Use the Spread Operator to Copy Arrays and Objects

Use the Spread Operator to Copy Arrays and Objects

The spread operator (...) is a useful feature in JavaScript that allows you to create copies of arrays and objects easily. It's handy when you want to avoid mutating the original data or when you need to merge data from multiple sources into a new array or object.

For more details, read my Spread Operator blog at the link below.

The Spread Operator in JavaScript

Copying Arrays:

You can use the spread operator to create a shallow copy of an array:

const originalArray = [1, 2, 3];
const copiedArray = [...originalArray];

console.log(copiedArray); // [1, 2, 3]

// Modifying the copied array doesn't affect the original
copiedArray.push(4);
console.log(originalArray); // [1, 2, 3]
console.log(copiedArray);   // [1, 2, 3, 4]

Copying Objects:

Similarly, you can use the spread operator to create a shallow copy of an object:

const originalObject = { name: 'Alice', age: 30 };
const copiedObject = { ...originalObject };

console.log(copiedObject); // { name: 'Alice', age: 30 }

// Modifying the copied object doesn't affect the original
copiedObject.city = 'New York';
console.log(originalObject); // { name: 'Alice', age: 30 }
console.log(copiedObject);   // { name: 'Alice', age: 30, city: 'New York' }

Merging Arrays:

You can also use the spread operator to merge multiple arrays into a new one:

const array1 = [1, 2];
const array2 = [3, 4];
const mergedArray = [...array1, ...array2];

console.log(mergedArray); // [1, 2, 3, 4]

Merging Objects:

For objects, you can merge their properties using the spread operator:

const object1 = { a: 1, b: 2 };
const object2 = { b: 3, c: 4 };
const mergedObject = { ...object1, ...object2 };

console.log(mergedObject); // { a: 1, b: 3, c: 4 }

The spread operator is a powerful tool for working with data in JavaScript, making it easier to create copies, merge data, and maintain data immutability.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment