Javascript Objects Pass by Reference

Just as you expect in your good ol’ compiled C# code (and other languages), JavaScript naturally passes its primitives by val, and its complex objects by reference. Depending on what your doing this could nuke something in your code if your not aware of it being passed this way. In some cases, passing an object by val is preferred!

In order to understand the scenario (in case your unfamiliar with it), following is an example showing a value in an object that we want to stay as “4”:


Now for the solution! Here is how to overcome the scenario quite easily:


You will notice the use of a function called “deepCopy”. This is a function you must include in your code to use as follows:

  2. // creates a dopy copy of a javascript object
  3. ‘object’

And thats how you do it! For the life of me, I cannot remember where I originally grabbed this nice little function from, but please advise if you know!

Leave a Reply