Middle
Are parameters passed to the function by reference or by value?
sobes.tech AI
Answer from AI
In JavaScript, function parameters are passed by value. However, it is important to understand that for primitive types (numbers, strings, boolean values), a copy of the value is passed, whereas for objects and arrays, a copy of the reference to the object is passed.
This means that if you modify the properties of an object inside a function, the changes will be visible outside the function because both inside and outside the function, the same object is being worked with. But if you assign a new object to the parameter inside the function, it will not affect the external object.
Example:
function modify(obj) {
obj.prop = 42; // modifies the original object
obj = { prop: 100 }; // assigns a new object locally
}
const myObj = { prop: 1 };
modify(myObj);
console.log(myObj.prop); // 42
Thus, parameters are passed by value, but for objects, this value is a reference.