I'm trying to understand the exact behavior of arrays in Javascript. I know that they work by reference. But I was confused when I came across this piece of code:
let arr1 = [1,2,3];
let arr2 = arr1;
arr1[2] = 4;
console.log(arr2); // [1,2,4]
arr1 = [2, 3, 4];
console.log(arr2); // [1,2,4] why not [2, 3, 4]
So how exactly do arrays behave in javascript?
arr1 = [2, 3, 4];, a new array[2, 3, 4]is created and assigned toarr1. That new array has nothing to do witharr2or the other array anymore.