Home > Web Front-end > JS Tutorial > What's the Difference Between Pass by Value and Pass by Reference in JavaScript?

What's the Difference Between Pass by Value and Pass by Reference in JavaScript?

Susan Sarandon
Release: 2024-12-22 13:49:10
Original
834 people have browsed it

What's the Difference Between Pass by Value and Pass by Reference in JavaScript?

Passing by Reference vs. Value in JavaScript

When passing data to functions in JavaScript, it's crucial to understand the difference between pass by reference and pass by value. This distinction affects how data is shared and modified between the function and the caller.

Pass by Value

For primitive data types (strings, numbers, booleans), JavaScript always passes by value. This means that a copy of the primitive value is created and passed to the function. Any changes made to the copy within the function have no effect on the original variable outside the function.

Pass by Reference

Objects (including arrays) are passed by reference in JavaScript. This means that the function receives a reference to the object, not a copy. Any changes made to the object's properties within the function will affect the original object outside the function.

Examples

Consider the following function:

function f(a, b, c) {
  a = 3;
  b.push("foo");
  c.first = false;
}
Copy after login

When called with the following arguments:

var x = 4;
var y = ["eeny", "miny", "mo"];
var z = {first: true};
f(x, y, z);
Copy after login

The value of x remains unchanged because it is passed by value. The original y array is directly modified via the push() operation, so its contents change. Similarly, the first property of z is modified, affecting the original object.

Independent Object Copy

To create a fully independent copy of an object, it's necessary to use a method that creates a new object with the same property values but no references to the original. One common approach is to use the JSON.parse(JSON.stringify()) technique:

var newObject = JSON.parse(JSON.stringify(originalObject));
Copy after login

The above is the detailed content of What's the Difference Between Pass by Value and Pass by Reference in JavaScript?. 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