Home >Web Front-end >JS Tutorial >What is the difference between Primitive Values and Reference Values in JavaScript?
Primitive Values vs Reference Values in JavaScript
In JavaScript, values can be classified into two categories: primitive values and reference values. Primitive values represent simple, immutable data types, such as numbers, strings, Booleans, null, and undefined. These values are stored directly in memory and are passed by value.
Primitive Value Storage
Primitive value storage is straightforward and efficient. The value itself is stored in memory as a sequence of bits. For example, the number 10 would be stored as a 32-bit integer in binary format. This approach allows for quick access and manipulation of primitive values.
Reference Values
On the other hand, reference values represent objects or data structures that are too complex to store directly in memory. Instead, reference values store the address (or reference) to the actual data in memory. This allows JavaScript to handle large and复杂数据结构 without consuming excessive memory.
When a reference value is assigned, the reference itself is copied from one variable to another. The referenced object, however, is not copied. Therefore, changes made to one variable will affect both variables. This distinction between copying references and objects is crucial for properly manipulating data in JavaScript.
Example
Consider the following code:
var foo = 123;
When this code executes, the value 123 is stored as a primitive value in memory. The variable foo holds a direct reference to this value. This means that any changes made through foo will reflect in the original value.
Additional Notes
The above is the detailed content of What is the difference between Primitive Values and Reference Values in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!