1. Distinction
1.1 Basic Data Types
The primitive data type is a simple data segment stored directly on the stack. Because it takes up little space and has a fixed size, it is frequently used data, so it is stored in the stack.
1.2 Reference Data Type
Objects of reference data type stored in the heap take up a lot of space and are not fixed in size. If stored in the stack, it will affect the performance of the program.
The reference data types in JavaScript are.
- Array
- Object
- Function
The reference data type is stored in heap memory, and then a reference to the actual object in heap memory is stored in stack memory (an address is stored in stack memory). Therefore, all operations on reference data types in JavaScript operate on references to objects rather than actual objects.
This is not a strict statement; when copying a scalar that holds some variable of the object, the operation is on the reference of the object. But when adding properties to an object, the operation is on the actual object.
2. Copy variable values
In addition to the difference in the way it is saved, there is also a difference when copying basic type values and reference type values from one variable to another.
2.1 Basic Data Types
For basic type values, if a copy is made, a new value is allocated on the stack memory for the new variable.
2.2 Reference Data Type
For reference data types like objects and arrays, if a copy is made, a new value is assigned to the new variable on the stack memory, but this value is just an address. That is, the copied variable has the same address as the original variable, pointing to the same object in heap memory.
Why do base data types exist in the stack and reference data types exist in the heap?
- The heap has more space than the stack, and the stack runs faster than the heap.
- Heap memory is unordered storage and can be accessed directly by reference.
- The base data type is more stable and occupies relatively less memory.
- The size of the reference data type is dynamic and infinite.