Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Describe pass by value and pass by reference in JavaScript?
JavaScript passes data to functions in two ways: pass by value for primitives (numbers, strings, booleans) and pass by reference for objects and arrays. Understanding this distinction is crucial for avoiding unexpected behavior in your code.
Pass by Value
In pass by value, a function receives a copy of the variable's value. Changing this copy inside the function doesn't affect the original variable. JavaScript primitives (numbers, strings, booleans, null, undefined) are always passed by value.
Example
<html>
<body>
<script>
let a = 1;
let change = (val) => {
val = 2;
console.log("Inside function:", val);
}
change(a);
document.write("Outside function: " + a);
</script>
</body>
</html>
Output
Outside function: 1
The variable a remains unchanged because the function received a copy of its value, not a reference to the original variable.
Pass by Reference
For objects and arrays, JavaScript passes a reference to the memory location where the data is stored. When you modify the object's properties inside a function, you're changing the actual object, not a copy.
Example 1: Mutating Object Properties
<html>
<body>
<script>
let a = {num: 1};
let change = (val) => {
val.num = 2; // Mutating the property
console.log("Inside function:", JSON.stringify(val));
}
change(a);
document.write("Outside function: " + JSON.stringify(a));
</script>
</body>
</html>
Output
Outside function: {"num":2}
The original object a was modified because we mutated its property num.
Example 2: Reassigning the Reference
<html>
<body>
<script>
let a = {num: 1};
let change = (val) => {
val = {num: 2}; // Reassigning, not mutating
console.log("Inside function:", JSON.stringify(val));
}
change(a);
document.write("Outside function: " + JSON.stringify(a));
</script>
</body>
</html>
Output
Outside function: {"num":1}
Here, a remains unchanged because we reassigned the parameter val to point to a new object, rather than modifying the existing one.
Key Differences
| Type | Behavior | Example |
|---|---|---|
| Primitives | Pass by Value | Numbers, strings, booleans |
| Objects/Arrays | Pass by Reference | Objects, arrays, functions |
Conclusion
JavaScript uses pass by value for primitives and pass by reference for objects. Remember that modifying object properties affects the original, but reassigning the parameter doesn't. This understanding helps prevent common bugs in JavaScript applications.
