DEV Community

loading...
Cover image for Does an object passed from a function is by reference or by value in JavaScript?

Does an object passed from a function is by reference or by value in JavaScript?

Mohammad Aziz
I write bugs 🐛
・2 min read

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);
}
Enter fullscreen mode Exit fullscreen mode

Can you see the difference? It's the * over there ☝️. Now let's run this function.

let gen = generator();
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

The result of calling next property is an object that is returned which has this type.

{value: any, done: boolean}
Enter fullscreen mode Exit fullscreen mode

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";
Enter fullscreen mode Exit fullscreen mode

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}
Enter fullscreen mode Exit fullscreen mode

Conclusion

This concludes that when we pass any object from a function, then it is passed by reference.

Discussion (0)