Skip to content

JavaScript Primitives vs Objects - Primitive vs Reference Types

المعرفة:: JavaScript
الحالة:: ملاحظة_مؤرشفة
المراجع:: The Complete JavaScript Course 2022 From Zero to Expert, JadeHendricks’s notes, JadeHendricks’s notes


In JavaScript we have two types of values (not everything is an Object).

  • Primitives
  • Numbers / BigInt
  • Strings
  • Symbol
  • Boolean
  • Undefined
  • Null
  • Objects
  • Arrays
  • Functions
  • Objects
  • Dates
  • Wrappers for Numbers, Strings, Booleans

It is natural to call numbers etc as primitive types while objects, arrays etc as reference types.

Primitives are stored in the call stack. It runs when the EC runs. References are stored in the call heap.

When we call a primitive:

  • JavaScript begins the EC in the call stack, by giving a memory address and also a value.

When we declare a variable as an object, the identifier is created which points to a piece of memory in the call stack which then references to a memory in the heap.

This is because the stack might be memory limited. As such, the object stored in the heap can be changed but the address in the call stack remains the same. This is because the memory address does not change!

Primitives and References in Function Parameters

file not exists

Cloning an Object

  • Shallow clone can be done using Object.assign().
const state = {  
  cart: [  
    { product: 'bread', quantity: 5 },  
    { product: 'pizza', quantity: 5 },  
  ],  
  user: { loggedIn: true },  
};  
const stateClone = Object.assign({}, state);  
state.user.loggedIn = false; // changes the original too!  
  • Deep clone can be done using lodash’s cloneDeep() method.
    import cloneDeep from 'lodash-es';  
    const stateDeepClone = cloneDeep(state);  
    

Last update : August 14, 2023
Created : August 23, 2022

Comments

Comments