Sobes.tech
Junior

How do you understand what pass-by-reference means?

sobes.tech AI

Answer from AI

In JavaScript, primitive data types (strings, numbers, booleans, null, undefined, Symbol, BigInt) are passed by value. This means that when assigning or passing to a function, the actual value is copied.

Objects (including arrays and functions) are passed and copied by reference. In fact, not the object itself is copied, but the reference to the memory area where it is stored.

// Pass by value
let a = 10;
let b = a; // Copies the value 10
b = 20;
console.log(a); // 10, changing 'b' does not affect 'a'

// Pass by reference
let obj1 = { value: 10 };
let obj2 = obj1; // Copies the reference to the object
obj2.value = 20;
console.log(obj1.value); // 20, changing through 'obj2' affects 'obj1' because they point to the same object

When passing an object to a function, the function receives a copy of the reference. Changing the object's properties inside the function will affect the original object because the reference is the same. However, if inside the function you assign a new object to the variable, the original variable remains unchanged because the reference will point to a different memory area.

function modifyObject(obj) {
  obj.newValue = 30; // Modifies the original object
}

function assignNewObject(obj) {
  obj = { anotherValue: 40 }; // The 'obj' variable inside the function now points to a new object
}

let myObject = { initialValue: 10 };
modifyObject(myObject);
console.log(myObject); // { initialValue: 10, newValue: 30 }

let anotherObject = { initialValue: 10 };
assignNewObject(anotherObject);
console.log(anotherObject); // { initialValue: 10 }, the original object did not change