Understanding Strange Array Returns

I try to understand the following:

var foo = [100, 2],
    bar = foo;

bar[0] = 9;

console.log(foo[0], bar[0]); // returns => 9, 9

I understand that it bar[0]returns 9 since it is set in this, but how does it foo[0]return 9 instead of returning 100?

It seems to have foobecome bar, so set it from right to left, and not from left to right

+4
source share
3 answers

Here foo, barboth point to the same place in memory. The actual array is shared between variables. So basically they both access / update the same array.

Non-primitive data types are not passed by value, they are passed by reference.

_______                _______
| foo | --> [...] <--  | bar |
|     |                |     |
-------                -------

, slice.

var bar = foo.slice();
+4

foo bar. :

bar = foo.splice(0);
0

since you assigned the variable foo to bar and they both use the same memory location, so the result will be the same.

0
source

Source: https://habr.com/ru/post/1613809/


All Articles