Cover Image for Shallow Copy in JavaScript
127 views

Shallow Copy in JavaScript

The JavaScript shallow copy refers to creating a new object or array that shares the same references to the elements of the original object or array. In other words, the new copy points to the same elements in memory as the original, without creating a new copy of each individual element.

There are several ways to perform a shallow copy in JavaScript, depending on whether you want to copy an object or an array. Here are a few examples:

  1. Shallow Copy of an Object:
JavaScript
 var originalObj = { name: 'John', age: 25 };
 var shallowCopy = Object.assign({}, originalObj);

In this example, Object.assign() is used to create a shallow copy of the originalObj. It takes an empty target object {} as the first parameter and the originalObj as the subsequent parameters. The properties of originalObj are copied into the new object, shallowCopy.

  1. Shallow Copy of an Array:
JavaScript
 var originalArr = [1, 2, 3, 4, 5];
 var shallowCopy = originalArr.slice();

Here, the slice() method is used with no arguments to create a shallow copy of originalArr. It returns a new array containing the same elements as the original array.

  1. Shallow Copy using Spread Operator (for both Objects and Arrays):
JavaScript
 var originalObj = { name: 'John', age: 25 };
 var shallowCopyObj = { ...originalObj };

 var originalArr = [1, 2, 3, 4, 5];
 var shallowCopyArr = [...originalArr];

The spread operator (...) can be used to create a shallow copy of both objects and arrays. It expands the elements of the original object or array into a new object or array, effectively creating a copy.

It’s important to note that a shallow copy only creates a new copy at the top level. If the original object or array contains nested objects or arrays, they will still be shared by both the original and copied versions. To create a deep copy (where nested elements are also copied), you would need to use more advanced techniques such as recursion or external libraries.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS