Does an object passed from a function is by reference or by value in JavaScript?
Mohammad Aziz
Posted on November 24, 2019
Lying on my bed, I started pondering one question in my mind. Whether the object passed by a function call is passed by reference or passed by value in the context of the function body?
How to evaluate this?
It was confusing at first that how should I test this? Because of once a function returns something, its body is done executing, so there wasn't any mechanism to check what happens to the object if we change it outside of the function body; whether will it be changed into the function as well?
Enters Generators
A generator function is a kind of function whose execution of the body can pause and can resume from the same spot from which It was paused before. So I created one simple generator function which I'll be using as the base to evaluate my theory.
function* generator() {
const me = {name: 'Aziz', age: 23};
rv = yield me;
console.log(me, rv);
}
Can you see the difference? It's the *
over there ☝️. Now let's run this function.
let gen = generator();
Calling the above function doesn't mean that the body will start executing from the same. When we run a generator function, it returns a generator object which has a property called next
, when we call this method, that is when the body of the generator function starts executing.
let myself = gen.next();
The result of calling next
property is an object that is returned which has this type.
{value: any, done: boolean}
Changing object's value
Now, I've got the passed object me
to the variable myself
. Let's try to change its value.
myself.value.name = "Mohammad Aziz";
One fascinating thing about the generators is that you can also pass value from outside to the stopped position of the generator. This is done by calling the same next
method and by passing the parameter you want to transfer to the generator body.
gen.next(myself.value);
// logs -> {name: "Mohammad Aziz", age: 23} {name: "Mohammad Aziz", age: 23}
Conclusion
This concludes that when we pass any object from a function, then it is passed by reference.
Posted on November 24, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024