Call by reference in JS

Call by reference in JS

Table of contents

In this article, I will explain and demonstrate how call by reference works in JS.

Definition

Let's follow these lines

"All the objects either formed by literal or by constructors uses call by reference but the primitive datatypes when initialized using literals use call by value."

Situations

  1. What do you think of it, will the object under the object2.text change as by following the call by reference? must provide the logic behind your answer. (Attempt it honestly you will get a lot out of it!!!)

    Answer: "NO! It won't" because there is not any call by reference between object1.text and object2.text both are referencing the same object literal but not themselves so change in one of the object's property won't change the other object property but if we make changes to the object literal to whom they are referencing then there should be a change in both the properties.

    Let's see an example:-

    Remember, while passing an argument to the function whatever the value argument offers is actually copied and passed to the function, and the snippet above demonstrates it

  2. So, by the above example, we get to know some clues about the call by reference and call by value let's try to answer this, will the properties change?

    Answer: Here it will work because now you are changing the "newData" object whose reference is held by both the properties and hence the value of both properties will change.

Is there any method by which I can show directly whether the objects share the reference to the same object or not?

Answer: Yes!, by using "===" because objects' assignment and comparison both are the game of reference (pointing to the memory location where the object is stored)

Here the "isReference" is holding "false" in both cases as I told you earlier both the properties has the reference to the "newData" but they don't have a reference of each other it is like a boy has two name "Ram" and "Raghav" both the name are pointing towards same the boy but the two names are not same.

Note: In JS using "==" or "===" the comparison will be done on the basis of reference and not by value but while deep comparison checks the objects' content, the deep comparison of both values will be true.

Bonus

Whenever you provide arguments to a function, then whatever the value is returned by the argument its copy is actually given to the function, which means if passed primitive ones like (5, "string") its copy of value will be given to the function or if the argument is an Object then its copy of reference will be passed to the function.

Did you find this article valuable?

Support Sahitya Aryan by becoming a sponsor. Any amount is appreciated!