Arrays - didn't understand the output

Why is console.log(foo[0]) showing 9 and not 1??

const foo = [1, 2];
const bar = foo;

bar[0] = 9;

console.log(foo[0], bar[0]);

And what is the purpose of using const?
PS - I guess i’m asking silly things here. I’ve lately started learning js.

In JS Objects (this means array as well) are passed by reference, this means that each reference access the same reference in memory.

To ease it up I have a mental model: whenever I save an Object, I’m not “storing” it in the variables, but somewhere on my computer’s memory.
What’s “inside” the variable is an “address” to where to find it later.

For example:

var a = []

A now hold an “address” in where the values are stored.

So if later i do

var b = a

Now b is pointing to the same “address” as A. So any change of b will change a, since both are referencing the same “space” in memory.

b[0] = 1

console.log(a) // [1]

Hope it helps :slight_smile: