JavaScript by reference vs. by value [duplicate]

I’m looking for some good comprehensive reading material on when JavaScript passes something by value and when by reference and when modifying a passed item affects the value outside a function and when not. I’m also interested in when assigning to another variable is by reference vs. by value and whether that follows any different rules than passing as a function parameter.

I’ve done a lot of searching and find lots of specific examples (many of them here on SO) from which I can start to piece together pieces of the real rules, but I haven’t yet found a single, well written document that describes it all.

Also, are there ways in the language to control whether something is passed by reference or by value?

Here are some of the types of questions I want to understand. These are just examples – I’m actually looking to understand the rules the language goes by, not just the answers to specific examples. But, here are some examples:

function f(a,b,c) {
   a = 3;
   b.push("foo");
   c.first = false;
}

var x = 4;
var y = ["eeny", "miny", "mo"];
var z = {first: true};
f(x,y,z);

When are the contents of x, y and z changed outside the scope of f for all the different types?

function f() {
    var a = ["1", "2", "3"];
    var b = a[1];
    a[1] = "4";
    // what is the value of b now for all possible data types that the array in "a" might hold?
}

function f() {
    var a = [{yellow: "blue"}, {red: "cyan"}, {green: "magenta"}];
    var b = a[1];
    a[1].red = "tan";
    // what is the value of b now and why?
    b.red = "black";
    // did the value of a[1].red change when I assigned to b.red?
}

If I want to make a fully independent copy of an object (no references whatsoever), what’s the best practice way to do that?

4 Answers
4

Leave a Comment