Search code examples
javascriptarraysreferencedynamic-arrays

How to Overcome this reference problem of this array in javascript


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);


Solution

  • 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);