Is JavaScript a pass-by-reference or pass-by-value language?

 

JavaScript is a "pass-by-value" language, but it can exhibit behaviors that appear to be "pass-by-reference" due to the way objects and variables work. To understand this distinction, let's explore JavaScript's behavior with examples.

  1. Pass-by-Value:

    • Primitive data types (e.g., numbers, strings, booleans) are passed by value. When you pass a primitive variable to a function, a copy of its value is created.
    javascript
  • function modifyValue(x) { x = 100; } let number = 42; modifyValue(number); console.log(number); // Output: 42

    In this example, number remains unchanged because the function modifyValue receives a copy of the value 42, not a reference to the original variable.

  • Pass-by-Reference (or Reference to an Object):

    • Objects (including arrays, functions, and custom objects) are passed by reference. When you pass an object variable to a function, you're actually passing a reference to the same object in memory.
    javascript
    1. function modifyObject(obj) { obj.prop = "Updated"; } let myObject = { prop: "Original" }; modifyObject(myObject); console.log(myObject.prop); // Output: "Updated"

      In this example, myObject is modified within the modifyObject function because the function receives a reference to the same object.

    It's important to understand that JavaScript passes everything by value, but for objects, the "value" being passed is a reference to the object. So, while it may look like pass-by-reference, it's still fundamentally pass-by-value.

    To clarify further, if you reassign an object variable within a function, it won't affect the original reference:

    javascript
    function reassignObject(obj) { obj = { newProp: "New Object" }; } let myObject = { prop: "Original" }; reassignObject(myObject); console.log(myObject.prop); // Output: "Original"

    In this case, myObject remains unchanged because the reassignObject function reassigns the parameter obj to a new object, but it doesn't affect the original reference outside the function.

    In summary, JavaScript uses "pass-by-value," but for objects, it's a "pass-by-value of a reference" where you're passing references to objects rather than the objects themselves. This behavior can sometimes lead to confusion, so it's important to be aware of how it works.

    Comments