What is call by reference and call by value in JavaScript?
In JavaScript, function arguments are passed by value, not by reference. This means that when you pass an argument to a function, a copy of the value is passed, not the original variable itself. Therefore, any changes made to the argument within the function are not reflected in the original variable outside the function.
For example, consider the following code:
let x = 10;
function changeValue(x) {
x = 20;
}
changeValue(x);
console.log(x); // 10
In this code, the changeValue
function takes an argument x
and changes its value to 20
. However, when the value of x
is logged outside the function, it still shows as 10
, which is the original value.
On the other hand, objects in JavaScript are passed by reference, meaning that when you pass an object to a function, the function receives a reference to the original object, not a copy. Therefore, changes made to the object within the function will be reflected in the original object outside the function.
For example:
let obj = { name: 'John' };
function changeObject(obj) {
obj.name = 'Jane';
}
changeObject(obj);
console.log(obj.name); // 'Jane'
In this code, the changeObject
function takes an object argument obj
and changes its name
property to 'Jane'
. When the value of obj.name
is logged outside the function, it shows as 'Jane'
, which is the updated value.
In summary, in JavaScript, function arguments are passed by value, but objects are passed by reference.