Memory Allocations in JS

Memory Allocation when dealing with JS “Primitives”

let myNumber = 23
  1. Allocate an address in memory (will be assigned at runtime).
  2. Store a value at the address allocated (23).
let newVar = myNumber
myNumber = myNumber + 1
let myString = 'abc'
myString = myString + 'd'

JavaScript’s memory model: the call stack and the heap

(1). call stack

Memory Allocation when dealing with JS “non-Primitives”

Non-primitive JS data types behave differently compared to primitive JS data types.

let myArray = []
  1. Allocate an address in memory (will be assigned at runtime).
  2. Store a value of a memory address allocated on the heap (will be assigned at runtime).
  3. The memory address on the heap stores the value assigned (the empty array []).

Let vs. const

In general, we should be using const as much as possible and only using let when we know a variable will change.

let sum = 0
sum = 1 + 2 + 3 + 4 + 5let numbers = []
numbers.push(1)
numbers.push(2)
numbers.push(3)
numbers.push(4)
numbers.push(5)

Why is it OK to declare an array using “const” ?

Let’s take a deeper dive on why it’s totally okay and preferred to declare the array using const.

const myArray = []
myArray.push(1)
myArray.push(2)
myArray.push(3)
myArray.push(4)
myArray.push(5)
myArray = 3
myArray = ['a']
const myObj = {}
myObj['newKey'] = 'someValue' // this will not throw an error

Google Recommendation:-

However, this is not recommended. Google, who has some of the best coders in the world, says in their JavaScript style guide, “Declare all local variables with either const or let. Use const by default, unless a variable needs to be reassigned. The var keyword must not be used” (source).

Experience with Front-end Technologies and MERN / MEAN Stack. Working on all Major UI Frameworks like React, Angular.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store