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 Primitive Types
  • let oldAge = age;
    • now oldAge points to the same address Primitive Types
  • age = 31
    • primitive types are immutable so when age is assigned 31 it must point to a new address Primitive Types

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) Reference Types
  • the friend object is created and me is assigned to it
    • like before (with age and oldAge) they both point to the same address in the call stack Reference Types
  • 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 and friend 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 Reference Types


  • Primitive and Reference Types: Primitive and Reference Types Code Primitive and Reference Types Output
  • Copying Objects with Object.assign(): Copying Object Copying Object
    • this is a shallow copy --- it only copies things in the first layer Shallow Copy Code Shallow Copy Output
      • 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

Copyright © 2022