One more thing hard to understand in JavaScript. | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
+ 8

One more thing hard to understand in JavaScript.

There is two variable a= 5 and b= a. After declare them we give another code a= 6. And the result after that is a= 6 and b= 5. Notice the result!! But, in another example: we have arrA =[0, 1] and arrB= arrA. After these code we add arrA[0] = 9. Then this strange thing happened. The result of the second example is arrA = 9, 1 and arrB = 9, 1. Why?? I wonder why does the arrB not remain its value like variable b in the first example? https://code.sololearn.com/WB2vwjz6C2I4/?ref=app

14th Jan 2018, 10:04 AM
Tran Huu Dang
Tran Huu Dang - avatar
2 Respostas
+ 11
Arrays are objects. And objects in js are copied by reference and not by value. So the reference point of both the arrays is same. If you want to create different arrays, use arrB=arrA.slice() This method clones the array.
14th Jan 2018, 10:20 AM
Swapnil Srivastava
Swapnil Srivastava - avatar
+ 3
@Swapnil Srivastava is right, but to explain a little further: There are two main type of values: primitives and mutable. Only objects and arrays (which are objects) are mutables values, even if you feel as primitives (numbers, strings...) are mutables. In fact, primitives are stored somewhere, and if you change the value of the variable holding this one, you store the new one elsewhere, and the variable now read its value at the new location. So, when refering to the value of a variable, the value itself is used (handling of memory location of the variable is done silently). When you store mutables values, you doesn't use directly the variable to store that value, but you store in it the location of the value: the reference of the mutable value. So accessing to the value (as copying it in another variable) will only access to its reference (location). And if you modify any of the copies, changes will be done on all variable refering to the same location...
14th Jan 2018, 11:49 AM
visph
visph - avatar