Middle+
What data types exist in JavaScript? How do primitives differ from objects? How are they stored in memory?
sobes.tech AI
Answer from AI
In JavaScript, the following data types exist:
Primitives:
- Number
- String
- Boolean
- Null
- Undefined
- Symbol
- BigInt
Objects:
- Object
- Array
- Function
- Date, RegExp, and other built-in objects
Differences between primitives and objects:
- Primitives are stored directly in the stack and are passed by value.
- Objects are stored in the heap, and the variable contains a reference to the object.
- Primitives are immutable, objects are mutable.
Memory storage:
- Primitives occupy a fixed space and are quickly accessible.
- Objects are stored in the heap, and variables contain pointers to them.
For example:
let a = 5; // a stores the value 5
let b = a; // copy of the value
b = 10; // a will not change
let obj1 = {x:1};
let obj2 = obj1; // obj2 and obj1 refer to the same object
obj2.x = 2; // obj1.x will also change
Thus, primitives are simple values, and objects are complex structures with reference semantics.