Home > Web Front-end > JS Tutorial > JavaScript Pass by Value or Reference: What's the Real Story?

JavaScript Pass by Value or Reference: What's the Real Story?

Mary-Kate Olsen
Release: 2024-12-28 17:27:55
Original
974 people have browsed it

JavaScript Pass by Value or Reference: What's the Real Story?

JavaScript: Pass by Reference vs. Pass by Value Demystified

In JavaScript, the topic of pass by reference versus pass by value often raises questions. Understanding this concept is crucial for effective programming.

Pass by Value vs. Pass by Reference

Contrary to popular belief, JavaScript always passes arguments to functions by value. However, the value passed can be a primitive data type (number, string, boolean, null, undefined) or a reference to an object (Array, Object).

Primitives vs. Objects

  • Primitives: Passed by their actual value. Modifications to the passed value do not affect the variable outside the function.
  • Objects (Arrays, Objects): Passed by reference. Modifications to the object's properties affect the variable outside the function. However, reassigning the entire object to a new reference will not affect the external variable.

Examples:

Consider the code snippet:

function f(a, b) {
  a = 3;
  b[0] = "foo";
}

var x = 4;
var y = ["eeny", "miny", "mo"];
f(x, y);
Copy after login
  • x remains unchanged because it's a primitive passed by value and reassigned.
  • y is modified because it's an object passed by reference and its property was modified.

Independent Object Cloning

To create a fully independent copy of an object without any references, the best practice is to use the Object.assign() method or the spread operator (...).

Example:

const original = { foo: "bar" };
const clone = { ...original };
Copy after login

In this example, clone is an independent copy of original. Any modifications to clone will not affect original.

The above is the detailed content of JavaScript Pass by Value or Reference: What's the Real Story?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template