Deep-copying in JavaScript
On the &quot;pass by value&quot; vs. &quot;pass by reference&quot; controversy, I see two issues here:<p>First, these terms have specific meaning in other languages such as C++, but JavaScript&#x27;s behavior does not match either of their definitions.<p>Second, there is a widespread myth that JavaScript passes primitive values and objects in two different ways. It doesn&#x27;t. They work exactly the same, and making an artificial distinction between them is not useful.<p>I find it helpful to make up some new terminology, so my thinking isn&#x27;t led astray by implied comparisons with other languages. I like to talk about <i>names</i> and <i>things</i>.<p>A <i>name</i> is a variable name or a parameter name.<p>A <i>thing</i> is any object or primitive value: anything that you can pass as a function argument or use on the right side of an assignment operator.<p>A name always refers to one thing. A thing can have multiple names.<p>When you pass an argument into a function, or when you use the assignment operator, you are giving a new name to an existing thing. If the name already referred to some other thing, that connection is lost. The name now refers to the new thing, and only to the new thing.<p>Everything works this way, primitives and objects alike.<p>The reason it&#x27;s often claimed that objects are passed into a function by reference, while primitives are passed by value, is that we instinctively write <i>different code</i> for the two cases. That different code is what leads to the notion that objects and primitives are treated differently.<p>If you pass an object into a function and you want to add or change a property of that object, you&#x27;ll naturally write:<p><pre><code>  function foo( obj ) {
      obj.myprop = 42;
  }
</code></pre>
But if you know the function is going to receive a primitive value, you won&#x27;t write this:<p><pre><code>  function foo( val ) {
      val.myprop = 42;
  }
</code></pre>
If you do, you&#x27;ll find out soon enough that it won&#x27;t work. It will throw an exception in strict mode, or fail silently in non-strict mode.<p>Instead you may write:<p><pre><code>  function foo( val ) {
      &#x2F;&#x2F; Do stuff here with val
      val = 42;
      &#x2F;&#x2F; Do stuff here with the *new* val, which isn&#x27;t the old val
  }
</code></pre>
The reason the functions behave differently is not because JavaScript passes primitives and objects differently. It doesn&#x27;t; they are all treated the same.<p>But primitives are <i>immutable</i>. They have no properties that we can change. We know that, or we find out if we try, so we simply don&#x27;t write code that tries to change a property of a primitive value.<p>It isn&#x27;t the JavaScript language that treats objects vs. primitives differently when passed into a function or when used in an assignment statement. We programmers do, by writing different code for the two.<p>(Edited for clarity)