Sobes.tech
Junior — Middle

How is argument passing implemented when calling functions in JavaScript?

sobes.tech AI

Answer from AI

In JavaScript, argument passing in functions is by value for primitive types and by reference for objects (but the reference itself is passed by value).

  • For primitives (numbers, strings, booleans), a copy of the value is created when calling the function, and changes inside the function do not affect the external variable.
  • For objects (objects, arrays, functions), a copy of the reference to the object is passed to the function, so changes to the object's properties inside the function are reflected on the original.

Example:

function modifyPrimitive(x) {
  x = 10;
}

function modifyObject(obj) {
  obj.value = 10;
}

let a = 5;
modifyPrimitive(a);
console.log(a); // 5 — unchanged

let b = { value: 5 };
modifyObject(b);
console.log(b.value); // 10 — changed

Thus, arguments are passed by value, but for objects, this value is a reference to the object.