+ 2

Can somebody explain to me how this works?

var arr1 = [1, 2, 3] ; var arr2 = arr1 ; arr1[0] = 4 ; Why is document.write(arr2[0]) 4? Isn't it supposed to be 1?

3rd Jan 2017, 5:28 PM
David Sebastian Keshvi Illiakis
David Sebastian Keshvi Illiakis - avatar
12 Answers
+ 9
You linked those two arrays together so when arr1[0] changes, arr2[0] gets the same value.
3rd Jan 2017, 5:35 PM
Valen.H. ~
Valen.H. ~ - avatar
+ 7
I think this happens only on object linking (array is an object)
3rd Jan 2017, 5:41 PM
Valen.H. ~
Valen.H. ~ - avatar
+ 6
Simply arr2 is copying the address of arr1. The reference is copying. So you can access arr2 as like arr1.
3rd Jan 2017, 5:45 PM
Sachin Artani
Sachin Artani - avatar
+ 3
My Javascript is a bit rusty, but if it's the same as in C it works like this: By saying arr2 = arr1 you basically point arr2 to exactly the same array as arr1, it won't just copy the values. So if you change something at arr1 it will also be changed in arr2. The arr variable only holds the position of the array, not it's values!
3rd Jan 2017, 5:33 PM
Robobrine
Robobrine - avatar
+ 3
@Gavin Christians Yeah it appeared in one of our challenges. I KNEW the answer and what's wrong with asking the explanation out of it? I don't see anything wrong with that? It's not that I just merely asked for the answer out.
3rd Jan 2017, 11:13 PM
David Sebastian Keshvi Illiakis
David Sebastian Keshvi Illiakis - avatar
+ 3
Nothings wrong with it, I meant no offence. I was just pulling your leg, cause it's friendly competition ;) Hope to challenge you again soon, this time I'll win
3rd Jan 2017, 11:21 PM
Ghauth Christians
Ghauth Christians - avatar
+ 2
xd this is confusing. However, if var a = 10 ; var b = a ; a = 20 ; b will maintain its value, which is 10. Why JS? Why?
3rd Jan 2017, 5:38 PM
David Sebastian Keshvi Illiakis
David Sebastian Keshvi Illiakis - avatar
+ 2
Makes sense, anyway thanks! I wonder if this works with null...
3rd Jan 2017, 5:41 PM
David Sebastian Keshvi Illiakis
David Sebastian Keshvi Illiakis - avatar
+ 2
As I said, you arr1 and arr2 variable hold the position of the array in memory, not it's actual values. By setting arr2 = arr1 they both point at the same position, meaning the same array. Normal variables just hold a value, so if you set b = a, b will now have the value of a.
3rd Jan 2017, 5:43 PM
Robobrine
Robobrine - avatar
+ 2
Hey...I never test this thing!
3rd Jan 2017, 5:47 PM
Yanothai Chaitawat
Yanothai Chaitawat - avatar
+ 2
lol you're looking for an answer to beat me again cheeze. Not fair but okay because we all need to learn
3rd Jan 2017, 7:15 PM
Ghauth Christians
Ghauth Christians - avatar
+ 2
I'm going to bed again, I shouldn't have woken up this early.
3rd Jan 2017, 11:22 PM
David Sebastian Keshvi Illiakis
David Sebastian Keshvi Illiakis - avatar