14
#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.
->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.
![](https://res.cloudinary.com/practicaldev/image/fetch/s--PvIAsmr0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c5gott6w1kib3z9a7fm1.png)
✅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'.
->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.
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.
14