Note that there are some explanatory texts on larger screens.

plurals
  1. POJavascript by reference vs. by value
    primarykey
    data
    text
    <p>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.</p> <p>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.</p> <p>Also, are there ways in the language to control whether something is passed by reference or by value?</p> <p>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:</p> <pre><code>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); </code></pre> <p>When are the contents of x, y and z changed outside the scope of f for all the different types?</p> <pre><code>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? } </code></pre> <p>If I want to make a fully independent copy of an object (no references whatsoever), what's the best practice way to do that?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload