Home >Web Front-end >JS Tutorial >Pass-by-Value vs. Pass-by-Reference in JavaScript: How Do They Affect Function Arguments?
Understanding Pass-by-Value and Pass-by-Reference in JavaScript
When passing values or objects to functions in JavaScript, it's crucial to understand the concept of pass-by-reference and pass-by-value. In short, primitives (such as numbers, strings, booleans) are passed by value, meaning any changes made within the function do not affect the original value outside the function.
However, objects are passed by "copy of a reference." This means that when an object is passed to a function, a new reference is created to the original object. Any changes made to the object's contents within the function will affect the original object.
Case Study: Rectangle Function Example
In the provided example, we have a rectangle function that takes a config object and an optional my object. Internally, it defines a local my object if it doesn't exist in the arguments. This my object stores the length and width of the rectangle.
The area function within the rectangle function calculates the area of the rectangle using the length and width stored in the my object.
When we invoke the rectangle function and assign the returned object to myRec, we create a copy of the reference to the my object. Any changes made to the contents of my (e.g., updating my.l and my.w) within the rectangle function will be reflected in both my and myRec because they refer to the same underlying object.
However, if we try to overwrite the reference to my within the rectangle function, it will not affect the copy of the reference held by the caller (myRec). This is because references are passed by value, meaning assigning a new object to my within the function only modifies the local reference, not the reference held by the caller.
The above is the detailed content of Pass-by-Value vs. Pass-by-Reference in JavaScript: How Do They Affect Function Arguments?. For more information, please follow other related articles on the PHP Chinese website!