Home >Web Front-end >JS Tutorial >What's the Difference Between Primitive and Reference Values in JavaScript?
Primitive vs Reference Values in JavaScript
In programming, variables can store two types of values: primitive values and reference values.
Primitive Values
Primitive values are simple, immutable data types such as numbers, strings, and booleans. They are stored directly in the variable's memory space.
Reference Values
Reference values are references to objects stored elsewhere in memory. They do not store the object itself, but instead contain the memory address pointing to it.
Storing of Variables
In JavaScript, primitives are stored in the variable's memory space. For example, if you assign the value 10 to a variable called x:
var x = 10;
The number 10 is stored directly in x's memory.
On the other hand, objects (including arrays, objects, and functions) are allocated from the heap. When you assign an object to a variable, the variable will store the reference (memory address) of the object, not the object itself.
var object = { a: 1, b: 2 }; var reference = object; // `reference` is now a reference to `object`
Value vs Reference Pass-by
When passing variables to functions, primitives are passed by value (a copy of the actual value is made). Reference values, however, are passed by reference (the reference itself is passed). This means that any changes made to the object through the reference variable will be reflected in the original object as well.
Conclusion
Understanding the difference between primitive and reference values is crucial for working with variables in JavaScript. Primitives are stored directly in the variable's memory, while references contain the address pointing to objects stored elsewhere in memory. Pass-by value for primitives ensures independent copies, while pass-by reference for objects allows for modifications to be synchronized across the original object and its references.
The above is the detailed content of What's the Difference Between Primitive and Reference Values in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!