👍 Primitive Types
Primitive types in JavaScript include Number, String, Boolean, Null, Undefined, Symbol, and BigInt. These types are immutable and are stored directly in the variable's memory location.
👉 Memory Behavior :
- When a primitive value is assigned to a variable, the value itself is stored in the variable's memory location.
- When the variable is assigned to another variable, the value is copied. Changes to one variable do not affect the other.
- When the variable is Re-assigned , the value is stored in the new memory location.
Explanation , of Above Example : 👇
The variable "a" is declared and initialized with the value 10. This means a directly stores the value 10 in its memory location.
The variable "b" is declared and initialized with the value of "a". Since "a" holds a primitive value, "b" gets a copy of that value. At this point, "b" also stores the value 10 in its own memory location. Now, both "a" and "b" have the value 10, but they are stored in separate memory locations.
Now variable "b" is reassigned with the value 20. This changes the value stored in b's memory location to 20. The variable "a" remains unchanged and still holds the value 10 because hey are stored in separate memory locations.
👍 Reference Types
Reference types include Object, Array, Function, and other objects created using the new keyword. These types are mutable and are stored as references to their memory locations.
👉 Memory Behavior :
When a reference type value is assigned to a variable, the variable stores a reference (or pointer) to the location in memory where the value is actually stored.
When the variable is assigned to another variable, only the reference is copied, not the value itself. Changes to one variable affect the other because they both reference the same object.
Explanation , of Above Example : 👇
Here "obj1" is a object . In JavaScript Object is Reference Data Types , meaning they are stored in memory, and variables store references (or pointers) to those objects. "obj1" is assigned a reference to an object with a property name set to "Alice".
"obj2" is assigned the same reference as "obj1". Now, both "obj1" and "obj2" point to the same object in memory.
Changing the name property of the object through "obj2" also affects "obj1" because both variables reference the same object.
This distinction between primitive values and objects/references is crucial for understanding how variables interact with memory in JavaScript, particularly when using let for variable declarations.
Top comments (1)