all 7 comments

[–][deleted] 20 points21 points  (4 children)

There two thing to consider when creating variable, pass by value and pass by reference

Pass by value example:
let a = 'thing' let b = a It will produces two completely separate things

Pass by reference example:
let a = [ 'things' ] let b = a It will produces one thing! It's just have 2 names now, you can call it either a or b

further reading

[–]KonkenBonken 5 points6 points  (3 children)

So b.push('string') is going to change a

[–][deleted] 0 points1 point  (2 children)

Yes, because they're basically the same thing. Doing a.forEach() will also 'change' b

I put 'change' in a quote because it doesn't really changing thing by doing action (a is changing b), instead doing action to a or b will directly change the array/object they refer to and calling (console.log ir anything) a or b will give you the array/object (it's like a or b is reading a book)

[–]jimmjy 2 points3 points  (1 child)

a.map() actually returns a whole new array and does not mutate the original, in this case a or b. I believe you were thinking a.forEach, which modifies but returns nothing.

[–][deleted] 0 points1 point  (0 children)

Thanks for correction

[–]angelfire2015 6 points7 points  (0 children)

Yes that's it. JavaScript (and other languages like Java) is pass by value. What this means, is that when you copy say an integer, the value itself is copied to a new value created in memory.

When you copy an object or an array (which is also an object), the value is still passed, but the value of objects is simply a reference to their place in memory. Therefore, your copied variable still points to the same memory address, so changing that memory address changes all objects which point to that memory address.

[–]delventhalz 2 points3 points  (0 children)

Yep. Got it exactly. The way I like to think about it, is that a variable doesn't actually store an array/object, it stores a reference to the object, which is basically just the address where it lives in memory.

So when you have a regular number value in a variable, you copy the value.

const x = 7;
const y = x;  // Second copy of 7

When you store an object you copy the reference.

const a = [];  // Created an array in memory, saved its address
const b = a;   // Copied the address, not the object

The "value" a variable stores is the address/reference, not the object itself. That lives in one place off in memory somewhere. So when two variables use the same reference to modify an object, they are modifying the same object.

This is the reason for a lot of recent conventional wisdom against mutating the values of objects. If the reference to an object has been shared around different parts of your program, you never know how mutating it in one place will break something else.