DEV Community

sofaki000
sofaki000

Posted on

Heap and Stack in JS basics

Javascript knows two types of memories: Stack and Heap

  • Stack
  1. easy-to-access memory
  2. Only items for which the size is known in advance can go onto the stack
  3. Numbers,strings,booleans go to the stack
  • Heap
  1. For items of which the exact size and structure can't be pre-determined.
  2. Objects and arrays can be changed at runtime, therefore they go to heap

For each heap item, the exact address is stored in a pointer which points at the item in the heap. This pointer in turn is stored on the stack.
For reference types, only pointers are stored on the stack.

Example 1
So for example, if you have the variable:

var person={name:"Sofia"}

Only a pointer to the person object is stored in that variable

Example 2

var person = { name: 'Sofia' }
var newPerson = person
newPerson.name = 'John'
console.log(person.name)
Enter fullscreen mode Exit fullscreen mode

This will print "John", becasue we never copied the person object itself to newPerson. We only copied the pointer, which still points at the same address in memory! Hence changing newPerson.name also changes person.name because newPerson points at the exactly same object!
You're pointing at the same object, you didn't copy the object.

How you copy the actual value? The spread operator comes to the rescue

var person = { name: 'Max' }
var copiedPerson = { ...person }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)