Memory size of javascript primitive types
Javascript is a dynamically-typed language. That doesn’t mean that it doesn’t have a type. The type is determined at runtime based on the variable’s value at the time. I wrote this article to explain the types and the memory size of each type. This knowledge can be really useless when creating simple web pages. But it is meaningful if it has to be highly optimized.
TL;DR
- Number : 8 bytes
- Boolean : Actually 1 bit. But initially, all JavaScript implementations used tagged pointers to represent JS values. This is an old trick that comes from the observation that allocated memory takes up at least 4 or 8 bytes, and are aligned in such a way that the least significant bit or three will be zero.
- String : A set of “elements” of 16-bit unsigned integer values. Because string is not a fixed value, the variable assigned a string does not contain the string but the reference to it. But, it behaves like a primitive type.
- null
- undefined
- Symbol
Everything else is object. It is called a reference value. Objects can be of any length, they do not have a fixed size. The same is true of arrays: an array can have any number of elements. Similarly, a function can contain any amount of JavaScript code. Since these types do not have a fixed size, their values cannot be stored directly in the eight bytes of memory associated with each variable. Instead, the variable stores a reference to the value.
Reference