![]() |
VOOZH | about |
JavaScript handles variables in different ways when passing them to functions. Variables in JavaScript can either be passed by value or passed by reference, depending on the type of data they hold.
When a variable is passed by value, a copy of the actual value is passed to the function. Any changes made to the parameter inside the function do not affect the original variable.
In JavaScript, primitive data types are passed by value. These include:
Inside function: 20 Outside function: 10
In this example
n (10) is copied to x.x inside the function does not affect n because x is a separate copy.When a variable is passed by reference, a reference to the actual data is passed. This means changes made to the parameter inside the function affect the original variable.
In JavaScript, non-primitive data types (such as objects and arrays) are passed by reference.
Inside function: Arun Outside function: Arun
In this example the obj reference is passed to the function, allowing changes to the original object.
| Feature | Pass by Value | Pass by Reference |
|---|---|---|
| Applies To | Primitive data types | Non-primitive data types (objects, arrays) |
| Data Copy | Creates a copy of the actual value | Passes a reference to the original data |
| Effect of Changes | Changes inside the function do not affect the original variable | Changes inside the function affect the original variable |
| Use Cases | Numbers, strings, booleans, etc. | Arrays, objects, functions |
JavaScript does not have "true pass by reference." Instead:
Inside function: Arun Outside function: Ravi
In this example
Thus, JavaScript passes reference values for objects but not "by reference" as in languages like C++.
When working with objects or arrays, be cautious of unintended changes to the original data.
To avoid modifying the original object, create a shallow or deep copy.
Ravi
Deep Copy
25