JavaScript Pass-by-Value vs. Pass-by-Reference
In JavaScript, all variables are passed by value, which means that a copy of the original value is made and passed to the function. However, when the value is an object, such as an array or an object literal, the copy is a reference to the original object.
Impact on Function Arguments
-
Primitive: When a primitive (e.g., number, string) is passed to a function, any changes made to that value within the function are limited to the local scope of the function and do not affect the original variable outside the function.
-
Object Reference: When an object reference is passed to a function, changes made to the object's properties within the function are reflected in the original object, even outside the function.
Impact on Variables Outside Functions
-
Pass-by-Reference: Object references are passed by reference, meaning that changes made to the object's properties within a function will affect the original object's properties, but any changes made to the reference itself (e.g., reassignment) within the function do not affect the original variable.
-
Pass-by-Value: Primitive values and object references passed by value do not affect the original variable outside the function.
Examples
1 2 3 4 5 6 7 8 9 10 11 12 | function f(a, b, c) {
a = 3;
b.push( "foo" );
c.first = false;
}
const x = 4;
let y = [ "eeny" , "miny" , "mo" ];
let z = { first: true };
f(x, y, z);
console.log(x, y, z.first);
|
Copy after login
In the example above, the changes to the b and c objects are reflected in the original objects, while the reassignment of a has no effect.
In-depth Examples:
1 2 3 4 5 6 | function f() {
const a = [ "1" , "2" , { foo: "bar" }];
const b = a[1];
a[1] = "4" ;
console.log(b);
}
|
Copy after login
In the first example, even though a has been modified, b still holds the original value because it is a copy of the reference.
1 2 3 4 5 6 7 8 | function f() {
const a = [{ yellow: "blue" }, { red: "cyan" }, { green: "magenta" }];
const b = a[1];
a[1].red = "tan" ;
console.log(b.red);
b.red = "black" ;
console.log(a[1].red);
}
|
Copy after login
In the second example, the change to a[1].red affects both a and b because they share the same object reference.
Creating Independent Copies
To create a fully independent copy of an object, you can use the JSON.parse() and JSON.stringify() methods to deserialize and serialize the object respectively. For example:
1 2 | const originalObject = { foo: "bar" };
const independentCopy = JSON.parse(JSON.stringify(originalObject));
|
Copy after login
The above is the detailed content of How Does JavaScript Handle Pass-by-Value and Pass-by-Reference with Primitive Types and Objects?. For more information, please follow other related articles on the PHP Chinese website!