0
Why does this modify the original array
var arr1 = [1,2,3]; var arr2 = arr1; arr2[0] = 4; console.log(arr1)//[4,2,3]
4 Réponses
+ 2
Because both the variables arr1, arr2 are pointing to the same memory location and when you change one variables value the other will be changed automatically
+ 2
Because in javascript objects are assigned by reference. It means those variables point to the same object, you are not creating a new one. Variable arr2 receives reference of arr1!
+ 2
in js, arrays and objects are mutable, so when you do an assignment like:
var arr2 = arr1;
you're not actually copying the array, you're assigning like a copy of reference. ("arr2" is really just a reference to "arr1", not an actual copy).
more about mutable and immutable:
https://benmccormick.org/2016/06/04/what-are-mutable-and-immutable-data-structures-2
0
Thanks guys for help. All of your answer seem to be same to me. That's why I marked the first answer. Thanks a lot.