Sunday, March 12, 2017

JavaScript fundamentals - pass by value / pass by reference

In this post, I would like to make a few simple examples showing the way JavaScript handles the standard programming language features -  pass by reference and pass by value.

A very good summation of JS behavior in this area is given here at StackOverflow post:

  • Javascript is always pass by value, but when a variable refers to an object (including arrays), the "value" is a reference to the object.
  • Changing the value of a variable never changes the underlying primitive or object, it just points the variable to a new primitive or object.
  • However, changing a property of an object referenced by a variable does change the underlying object.
Based on these facts, we can easily resolve the following simple operation:

var a=12;



since a and b are primitive types:
a is now 13
b is now 14
Here is a Fiddle of a more complex scenario. This scenario shows an example of dealing with objects and arrays. It's clear that that in case of assignment operation with objects, the JS will behave as any other language which uses "pass by reference":

No comments:

Post a Comment

Ubuntu 12.04, 14.04, 16.04 - auto start an app or script before login

To run a command or application at startup, even before the user has logged in, you can use this file: /etc/rc.local The commands entered...