Home >Web Front-end >JS Tutorial >Pass-by-Reference vs. Pass-by-Value in JavaScript: How Do Objects and Primitives Behave in Function Calls?

Pass-by-Reference vs. Pass-by-Value in JavaScript: How Do Objects and Primitives Behave in Function Calls?

DDD
DDDOriginal
2024-12-20 21:44:09148browse

Pass-by-Reference vs. Pass-by-Value in JavaScript: How Do Objects and Primitives Behave in Function Calls?

JavaScript Pass-by Reference vs. Pass-by Value

JavaScript employs both pass-by-value and pass-by-reference mechanisms. Primitives, such as numbers and strings, are passed by value, meaning a copy of the primitive is created in the called function. In contrast, non-primitives, primarily objects, are passed by reference.

In the case of objects, a reference to the object is passed rather than a copy. This means that modifying the reference variable in the called function will not affect the reference in the caller, as demonstrated in the example provided:

var a = { key: 'value' };
replace(a); // a still holds its original value
update(a); // a's contents change

Confusion with the rectangle Function

The example in the question includes a nested function rectangle with the my parameter. This parameter is initially undefined, but is defined within the function. The reason for this setup is to provide a way to share data between the rectangle function and its inner area function.

While the my parameter is not initially defined in the rectangle function, it is an object reference passed by reference. As such, when it is assigned within the rectangle function, it creates a new reference to an object that can be modified both within the rectangle and area functions, even though the area function does not directly receive the my parameter.

The above is the detailed content of Pass-by-Reference vs. Pass-by-Value in JavaScript: How Do Objects and Primitives Behave in Function Calls?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn