variables declaration and storing | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

variables declaration and storing

Just had a challenge in JS and the correct answer left me puzzled: var arr1=[4,7,2]; var arr2=arr1; arr1[0] = 5; console.log(arr1[0]+arr2[0]); surprisingly, the correct answer is 10, not 9 as I have expected. my question is, why arr2 changes along with arr1, although it is not stated explicitly. does the initial assignment arr2=arr1 that arr2 is bound to arr1, not just stores the values arr1 had?

9th Oct 2019, 7:18 AM
Ilia Sinev
Ilia Sinev - avatar
1 Answer
+ 3
Array is reference data types which mean it is not copied as a whole value like primitive data types, rather it is copied as a reference, when you copy an array to another variable, the array is not duplicated which is why changes in arr1 is applied to arr2 too. If you want to clone the array use arr2 = [...arr1] which will create a new array.
9th Oct 2019, 7:33 AM
Rizky
Rizky - avatar