Javascript knows two types of memories: Stack and Heap
- Stack
- easy-to-access memory
- Only items for which the size is known in advance can go onto the stack
- Numbers,strings,booleans go to the stack
- Heap
- For items of which the exact size and structure can't be pre-determined.
- 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)
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 }
Top comments (0)