Thursday, 21 November 2024

How to create a shallow copy of an array in Javascript?

Using the spread operator (...), we can create a shallow copy of the arr array.

Example

newArray = [...arr]

 

·      arr: This is the original array that you want to copy. It could contain any elements, such as numbers, strings, objects, or other arrays.

 

·      Spread Operator (...): The spread operator ... is used to "spread out" the elements of an iterable (like an array or a string). When used inside an array literal (i.e., within []), it spreads out the individual elements of arr into the new array.

 

·      newArray: This is the new array that gets the copied elements. It will have the same elements as arr but is a different array in memory.

 

shallowCopy.js

let arr = [1, 2, 3];
let newArray = [...arr];

console.log(`arr : ${arr}`);
console.log(`newArray : ${newArray}`);
console.log(`newArray === arr : ${newArray === arr}`); 

console.log('\nAdding new element 4 to the newArray');
newArray.push(4);

console.log(`\narr : ${arr}`);
console.log(`newArray : ${newArray}`);
console.log(`newArray === arr : ${newArray === arr}`);

 

Output

arr : 1,2,3
newArray : 1,2,3
newArray === arr : false

Adding new element 4 to the newArray

arr : 1,2,3
newArray : 1,2,3,4
newArray === arr : false

 

The code demonstrates the behaviour of shallow copying in JavaScript using the spread operator. It starts by creating an array arr and then creates a shallow copy of it called newArray. Initially, both arrays contain the same elements [1, 2, 3], but they are distinct objects in memory (newArray === arr returns false). After adding a new element (4) to newArray, the original arr remains unchanged, illustrating that modifications to the shallow copy do not affect the original array.

 

The spread operator creates a shallow copy, which means it only copies the first level of the array. If the array contains objects or other arrays, the references to those objects or arrays are copied, not the objects or arrays themselves.

 

shallowCopyOnObjects.js

 

let arr = [1, 2, {a: 3}];
let newArray = [...arr];

console.log(`arr : ${arr}`);
console.log(`newArray : ${newArray}`);
console.log(`arr[2].a : ${arr[2].a}, newArray[2].a : ${newArray[2].a}`)

console.log('\nUpdating first element of arr');
arr[0] = 111222;

console.log('Updating third element, which is an object')
newArray[2].a = 'Hello World!!!!';

console.log(`\narr : ${arr}`);
console.log(`newArray : ${newArray}`);
console.log(`arr[2].a : ${arr[2].a}, newArray[2].a : ${newArray[2].a}`)

 

Output

arr : 1,2,[object Object]
newArray : 1,2,[object Object]
arr[2].a : 3, newArray[2].a : 3

Updating first element of arr
Updating third element, which is an object

arr : 111222,2,[object Object]
newArray : 1,2,[object Object]
arr[2].a : Hello World!!!!, newArray[2].a : Hello World!!!!

 

The code demonstrates that using the spread operator (...) creates a shallow copy of an array, meaning it only duplicates the first level. When an array contains objects or other arrays, only references to those objects or arrays are copied, not the objects or arrays themselves. As a result, changes to the nested objects in either the original array or the shallow copy will affect both arrays, while changes to primitive elements only affect the specific array they are modified in. You can observe the same in above example, where the changes of the property ‘a’ are applied to both the arrays, but the primitives is not.

 


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment