Pass by Value or Pass by Reference?
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 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 .
- What is noscript tag?
- Difference between '=', '==' and '===' operators?
- What is Browser Object Model
- How to test a string as a literal and as an object ?
- What is Associative Array? How do we use it?
- What's the Difference Between Class and Prototypal Inheritance?
- Event bubbling and Event Capturing in JavScript?
- What is the difference between .call() and .apply()?
- What is an immediately-invoked function expression?
- What Are RESTful (REpresentational State Transfer)Web Services?