Memory allocation (allocated when a variable is created and reclaimed when not in use)

Stack for variables (basic data types)

Stack memory is stored last in first out similar to a barrel

Heap objects (reference data types)

Heap memory is stored in an orderly fashion

Js does not allow direct manipulation of heap memory locations. Therefore, in-heap operations that store reference type data are manipulating references rather than real objects

An address stored in stack memory (address pointer). This address is associated with heap memory and data stored in the stack can be shared (variable names are different but the contents to be stored are the same).

Heap memory runs faster than stack memory replication is redistributed independently of each other heap memory replication stack Pointers are different (reference names are different) but data objects still point to one

Eg: var a1 = 0; / / stack

var a2 = ‘this is string’; / / stack

var a3 = null; / / stack

var b = { m: 20 }; {m: 20} is stored as an object in the heap

var c = [1, 2, 3]; // The variable c is stored in the stack, and [1, 2, 3] is stored in the heap as an object

Original value: When a variable containing the original value is copied to another variable, a copy of the original value is assigned to the new variable. Thereafter, the two variables are completely independent (the original value is stored in stack memory, and each is an independent address).

Reference value: When a variable that holds the memory address of an object is copied to another variable, the memory address is assigned to the new variable. The two variables refer to an object in heap memory

Memory life cycle

Memory allocated in the JS environment generally has the following life cycle:

  1. Memory allocation: When we declare variables, functions, and objects, the system automatically allocates memory for them
  2. Memory usage: reading and writing memory, that is, using variables, functions, etc
  3. Memory reclamation: The garbage collection mechanism reclaims unused memory