NOTE: All images from Jonas Schmedtmann's The Complete Javascript Course 2020
Primitives vs. Objects (Primitive vs. Reference Types)
(technically primitives are stored in the execution contexts within the call stack, but for simplicities’ sake...)
Primitives Example
let age = 30;
age
is assigned an address and value
let oldAge = age;
- now
oldAge
points to the same address
- now
age = 31
- primitive types are immutable so when age is assigned 31 it must point to a new address
Reference Example
- a new object,
me
is stored in the heap- it has an address in the call stack with a reference to an address in the heap, which is where the object is actually stored (the heap is like an unlimited memory pool)
- the
friend
object is created andme
is assigned to it- like before (with
age
andoldAge
) they both point to the same address in the call stack
- like before (with
- then we change the
age
property of friend and both ages change- we did not change the value at the address in the call stack (which is immutable), we changed the value in the
heap => both
me
andfriend
are both still pointing to the same address in the call stack, which is still pointing to the same location in the heap, so the value has changed for both of them
- we did not change the value at the address in the call stack (which is immutable), we changed the value in the
heap => both
Examples
- Primitive and Reference Types:
- Copying Objects with
Object.assign()
:- this is a shallow copy --- it only copies things in the first layer
- the last name still changed because it is in the first layer --- but both objects got the array pushed to them because it is a deeply nested object (both the original and the copy both point to the array in the same place in the heap)
- a deep clone is much more complex and is usually done with an external library like lodash
- this is a shallow copy --- it only copies things in the first layer