Home > Net >  How to Overcome this reference problem of this array in javascript
How to Overcome this reference problem of this array in javascript

Time:08-06

even though both share the same memory location why this result is returning the same array [1,2,3,4,5] why not an empty array [];

let num = [1, 2, 3, 4, 5];
let result = num;
num = [];
console.log(result);

CodePudding user response:

This is because you don't modify but instead completely reassign a new Array() (=[]) to num. result would change too if you'd only mutate num e. g. with .push().

const num = [1, 2, 3, 4, 5];
const result = num;
num.push(6);
console.log(result);

CodePudding user response:

Because you just change the num reference value, not the array itself, as the result variable still points to the array, So the array is still in the memory.

let num = [1, 2, 3, 4, 5];
let result = num;
num = [];
console.log(result);

But if you re-assign num value before assignation with result, The array will be deleted from memory by garbage collection as it has no referance

let num = [1, 2, 3, 4, 5];
num = [];
let result = num;
console.log(result);

CodePudding user response:

As explaied by @Behemoth, when you reassign a new Array to num using = operator, result still point to the original array and num point to a new empty array.

If you use splice instead of reassigning empty array to num you can see that result is also modified, that is because splice modifed to array wherenum and result are both pointing in memory :

let num = [1, 2, 3, 4, 5];
let result = num;

num.splice(0, num.length);

console.log(num);
console.log(result);

  • Related