Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Wednesday, February 19, 2025

JavaScript, Pass By Value vs Reference in JavaScript

Explain Pass By Value vs Pass By Reference in JavaScript by examples.
Answer: In JavaScript, understanding pass by value and pass by reference is crucial for effectively manipulating data and understanding how variables behave when passed into functions. Let's break down each concept with examples:

When a variable is passed by value, a copy of the variable's value is passed into the function. Changes made to the parameter inside the function do not affect the original variable outside the function.
Example:

// Pass by value example
let num = 10;
function modifyValue(x) {
x = 20; // Changing the parameter value
}
modifyValue(num);
console.log(num); // Output: 10 (original value remains unchanged)

In this example:

  •  'num' is a variable holding the value '10'.
  •  When 'num' is passed to 'modifyValue', 'x' receives a copy of 'num''s value ('10').
  •  Inside 'modifyValue', 'x' is changed to '20', but this change only affects 'x' inside the function scope.
  •  Outside the function, 'num' retains its original value '10'.When a variable is passed by reference, the function receives a reference to the original variable.

Changes made to the parameter inside the function will affect the original variable outside the function.
Example:

// Pass by reference example
let obj = { value: 10 };
function modifyObject(o) {
o.value = 20; // Modifying the object property
}
modifyObject(obj);
console.log(obj.value); // Output: 20 (original object property is changed)

In this example:

  •  'obj' is an object with a property 'value' set to '10'.
  •  When 'obj' is passed to 'modifyObject', 'o' receives a reference to the same object that 'obj' points to.
  •  Inside 'modifyObject', 'o.value' is changed to '20'. This modification affects the original 'obj' because both 'obj' and 'o' reference the same object.
  •  Therefore, when 'console.log(obj.value)' is executed after the function call, it outputs '20', reflecting the change made inside the function. Pass by Value: Copies the actual value of an argument into the parameter of the function. Modifying the parameter inside the function does not affect the original variable.
  •  Pass by Reference: Copies the reference (address) to the memory location of the variable into the parameter. Modifying the parameter inside the function affects the original variable outside the function.

Understanding these concepts helps in avoiding unintended side effects when manipulating data within JavaScript functions.

Hot Topics