Net-informations.com
SiteMap  | About    

Pass by Value or Pass by Reference?

In JavaScript , we have functions and we have arguments that we pass into those functions. But how JavaScript handles what you're passing in is not always clear. There is no "pass by reference" for any variable in JavaScript. All variables and arguments are assigned by value, but for objects the value of the variable is a reference. Because of this, when you pass an object and change its members, those changes persist outside of the function. This makes it look like pass by reference . So, Primitive values like number, string, boolean are passed by value while Objects and arrays are passed by reference like above said.

With Primitive Data Types

In the case of Primitive Data Types , if you change the value of a Primitive Data Type inside a function, this change won't affect the variable in the outer scope. This means that any changes to that variable while in the function are completely separate from anything that happens outside the function. Let's take a look at the following example:

In the above example, we are changing the "toDay" variable inside of the function changeDay, and display it after calling the function, it still has the value "Sunday" . This is because when primitive types are passed by value. This means that any changes to that variable while in the function are completely separate from anything that happens outside the function. This is what is meant when we say we are passing by value in JavaScript.

With Objects

In the case of Objects , if you change the value of an Object property inside a function, this change will affect the variable in the outer scope . All variables and arguments are passed by value, but for objects the value of the variable is a reference. Passing by reference involves having two references point to the same object in memory. This means you can mutate and object or function by assigning it to another object or passing it as a parameter to a function. Let's take a look at the following example:

In the above example, we are changing the "toDay" variable inside of the function changeDay, and display it after calling the function, the value of toDay is changed to "Monday" . This is because when you pass an object into the function, you are not passing a copy. You are passing reference that points to the thisWeek object. So when you change a property of that object in the function, you are changing the property of the object in the outer scope .

Understanding the difference between pass by value and pass by reference is key to understanding how JavaScript objects and primitives work.









net-informations.com (C) 2018    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.