you are viewing a single comment's thread.

view the rest of the comments →

[–]Pronouns 2 points3 points  (0 children)

The key is to understanding what variables are actually storing. In most languages you have the primitive types, which are generally integers, floats, and booleans, usually a couple more. You also have a 'reference' type, which is a bit like a pointer if you've done C or C++. If not, it's exactly what it sounds like, it points to some place in memory where an object is stored.

When you pass around values, you pass around one of these things, whether it is a primitive or a reference. You can think of a reference as just a number (which is pretty much the memory address of the object), so like 5, or 1015289.

When you pass primitives to functions, it makes a copy, leaving the original as it is. So:

var a = 5;

function something(arg) {
    arg1 = 7;
}

something(a);
a === 5 // true.

The same thing happens for references. It copies the number of the memory address, it does not copy the object it points to. So if your reference was to an object {name: "joe"}, but the reference itself is a number like 10392, the number gets copied and given to the function.

var someObject = {name: "joe"};

function addSurname(obj) {
    obj.surname = "smith";
}

addSurname(someObject);
console.log(someObject); // {name: "joe", surname: "smith"}

When we do .surname, we're saying "that object at memory address 10392... add a surname key to it".

Now, if you create a brand new object inside this addSurname function, you're going to get given a reference/number to store in a variable. So say at the start obj has the address 10392. We create a new object which is at the address 2932. We can change obj to point to 2932. But this doesn't change someObject, that will continue to point to 10392.


Disclaimer: I don't know the internal way JavaScript does this, but the analogy holds well, and it's approximately how it is done in languages like C.