DEV Community

Cover image for #7) Explain pass by value & pass by reference❓
Mayank Yadav
Mayank Yadav

Posted on

#7) Explain pass by value & pass by reference❓

🔰In JavaScript, primitive data types is passed by value and non-primitive data types is passed by reference.

🚀Pass by Value:

->In pass by value, function is called by directly passing the value of the variable as an argument.

->Any change that you make to the argument inside the function does not effect the original value.

->Parameters passed as an argument creates it's own copy.
So, any changes inside the function will be on it's copy and not on the original value.

image
Let's see how it works👇

✅Firstly, define a passByValue function with an argument 'a'.

✅Declare and initialize the value of b = 1.

✅Then, pass the 'b' variable into the function, JavaScript copies the value of 'b' to the 'a' variable.

✅After that, the passByValue function changes the 'a' variable. However, this does not impact the original value of 'b'.

🚀Pass by Reference:

->In Pass by Reference, function is called by directly passing the reference/address of the variable as an argument.

->On changing the value inside the function also change the original value.

->In JavaScript array and Object follows pass by reference property.

->In Pass by reference, parameters passed as an arguments does not create its own copy, it refers to the original value so any changes made inside function will directly affect the original value.
image

Let's see how it works👇

✅Firstly, define the passByReference() function that accepts an object person. The function sets the name property of the object to Maverick.

✅Next, declare a variable friend and assign it an object whose name property is set to Ayush.

⚠The friend is a variable that references the actual object:
let friend = {name: "Ayush",};

✅Then, pass the friend variable into the function.

✅JavaScript copies the value of the friend variable to person variable.

✅As a result, both friend and person variables are referencing the same object in the memory: passByReference(friend);

✅After that, inside the function, the name property of the object is set to Maverick through the person variable.

✅Finally, accessing the name property of the friend variable returns Maverick.


Latest comments (0)