Primitive values and reference values in JavaScript
In JavaScript, variables can be assigned either primitive values or reference values. Primitive values, such as booleans, numbers, and strings, are stored directly in the variable's memory location.
When you create a reference value, such as an array or object, you are not actually storing the object or array itself in the variable. Instead, you are storing a reference to the location in memory where the object or array is stored. This means that if you change the object or array, the changes will be reflected in the variable, even though the variable itself has not changed.
Example
The following JavaScript code creates a primitive value and a reference value:
var name = "John"; // Primitive value stored in the variable var shoppingCart = []; // Reference value stored in the variable
In this example, the variable name contains the primitive value "John". The variable shoppingCart contains a reference to the array object stored in memory.
Passing values by value vs. by reference
When you pass a primitive value to a function, a copy of the value is passed. This means that any changes made to the value within the function will not affect the value stored in the variable.
When you pass a reference value to a function, the reference itself is passed, not a copy. This means that any changes made to the object or array within the function will also affect the object or array stored in the variable.
Example
The following JavaScript code demonstrates passing values by value and by reference:
// Pass by value var name = "John"; function changeName(name) { name = "Jane"; // Changes the local copy of the value } changeName(name); console.log(name); // Outputs "John" because the original value is not changed // Pass by reference var shoppingCart = []; function addProduct(shoppingCart) { shoppingCart.push("Apple"); // Changes the object stored in the reference } addProduct(shoppingCart); console.log(shoppingCart); // Outputs ["Apple"] because the original object is updated
In the first example, the function changeName is passed the primitive value "John". When the function changes the value to "Jane", the original value stored in the variable name is not affected.
In the second example, the function addProduct is passed the reference value shoppingCart. When the function adds the product "Apple" to the array, the original object stored in the variable shoppingCart is also updated.
The above is the detailed content of How do primitive values and reference values differ in JavaScript when passed to a function?. For more information, please follow other related articles on the PHP Chinese website!