Simple But Most People Miss Out On This ๐Ÿ˜Š Small Tips And Tricks For Javascript :

ยท

1 min read

REFERENCE AILISING :

var a = [1,2,3,4,5]
var b = a 
b.pop()
console.log(b)
console.log(a)

Output Expected : b = [1,2,3,4] and a=[1,2,3,4,5]

Actual output : b = [1,2,3,4] and a = [1,2,3,4]

The question arises why this happens.

It is very simple, in javascript we may think that we are creating another array which is a copy of the actual array. But It is not . We are not creating any copy of the actual array instead we are making a reference of the actual array in memory. As a result of which one change in array b is reflected to the actual array .

How to resolve the problem?

To resolve the problem mentioned above we just need this syntax which makes the copy of the actual array to another array and any change in the copied array will not affect the actual array !!

var a = [1,2,3,4,5]
var b = [...a]; 
b.pop()
console.log(b)
console.log(a)

Output : b = [1,2,3,4] and a=[1,2,3,4,5]

ย