Home > Web Front-end > JS Tutorial > body text

What's the Difference Between Primitive and Reference Values in JavaScript?

Barbara Streisand
Release: 2024-11-09 12:21:02
Original
322 people have browsed it

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;
Copy after login

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`
Copy after login

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!

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