In JavaScript, when an object is passed as an argument to a function, it is
passed by reference. This means that the function receives a reference to the original object, not a new copy of the object. Any modifications made to the object within the function will affect the original object outside of the function as well.
Here's an example to demonstrate this behavior:
function modifyObject(obj) {
obj.property = 'Modified';
}
const myObject = { property: 'Original' };
console.log(myObject); // { property: 'Original' }
modifyObject(myObject);
console.log(myObject); // { property: 'Modified' }
In the example above, the `modifyObject` function accepts an object as an argument and modifies its `property` value. When we pass `myObject` to the `modifyObject` function, the function receives a reference to `myObject`. As a result, modifying `obj.property` inside the function also modifies the `property` value of the original object, `myObject`.
It's important to note that this behavior applies to objects (including arrays and functions) but not to primitive types like numbers, strings, booleans, etc. Primitive types are passed by value, meaning that a new copy of the value is created and passed to the function. Modifying the value inside the function does not affect the original value outside of the function.
For example:
function modifyPrimitive(value) {
value = 'Modified';
}
let myValue = 'Original';
console.log(myValue); // 'Original'
modifyPrimitive(myValue);
console.log(myValue); // 'Original'
In this example, the `modifyPrimitive` function accepts a string as an argument. However, when we modify the `value` parameter inside the function, it does not affect the original value of `myValue` outside of the function.
In summary, when passing an object as an argument to a function in JavaScript, it is passed by reference. Any modifications made to the object inside the function will be reflected in the original object outside of the function.