Middle
How does memory work in JavaScript?
sobes.tech AI
Answer from AI
Memory in JavaScript is managed automatically. It is divided into two main areas:
- Heap: This is where objects and functions are stored. Memory is allocated dynamically when these entities are created.
- Stack: This is where primitive values (strings, numbers, booleans, null, undefined, Symbol, BigInt) and references to objects in the heap are stored. The stack operates on a LIFO (Last-In, First-Out) principle.
When a reference to an object is no longer used, the garbage collector frees up memory in the heap. Garbage collection algorithms can vary, but often marking and sweeping are used:
- Marking: The garbage collector scans all reachable objects from root nodes (global variables, local variables of the current function) and marks them as "alive".
- Sweeping: All unmarked objects (unreachable from root nodes) are considered "dead" and are removed from memory.
The garbage collector runs in the background automatically. Memory issues, such as leaks, occur when objects remain reachable even though they are no longer used according to the program logic.
Primitive values are copied by value, while objects and arrays are copied by reference.
// Example: primitive copied by value
let a = 5;
let b = a;
b = 10;
// a remains 5, b becomes 10
// Example: object copied by reference
let obj1 = { value: 10 };
let obj2 = obj1;
obj2.value = 20;
// obj1.value is now also 20, since obj2 references the same object