Javascript - Primitive vs Reference Values by Danny Reina
Summary: It’s all about memory!
To start, let's define what are primitives and references. In short, primitives are simple immutable building blocks of JavaScript. These are String
Number
Boolean
undefined
null
ES6 Symbol
& BigInt.
To further define a primitive, it’s important to understand that a primitive can be replaced but it can’t be directly altered & does not have properties/attributes. For example, null.length
will give you a TypeError
which demonstrates that primitives do not have properties.
Hold Up But I Can Do `this shouldn’t be possible`.length = 26
Whenever a primitive value is written, JavaScript automatically wraps the primitive value in a primitive wrapper object which allows the usage of methods like length
on string values, because objects do have properties. Take note, these primitive object wrappers do not apply to null
and undefined
.
var bar = "baz";
console.log(bar); // baz
bar.toUpperCase();
console.log(bar); // baz"baz".length // 3
isNaN(3) // false
null.length // TypeError
Let’s now define what references are. Simply put, references are pointers to values stored in variables and not pointers to other variables or references. That reference points to the object’s location in memory. The variables don’t actually contain the value.
author.name
does not store ‘Dany Reina’ it stores a pointer to a memory address that contains ‘Danny Reina’To explain, you have to understand what is going on behind the scenes. JavaScript stores the values you assign to properties or variables in memory. There are two types of memory JavaScript knows of, the Stack and the Heap. The stack is an easy to access memory region that allocates local context for each executing function. Meaning, during a function’s execution, all of its local variables are being stored in a call stack. After it’s finished executing, it is removed from the stack and the allotted memory frees up for the next function. Furthermore, only primitive values are stored on the stack. Everything else is dynamically allocated onto the heap.
The heap is a region of memory for items in which you can’t pre-determine the exact size and structure. Since objects can be mutated and change at runtime, they have to go into the heap. To fully understand how dynamic memory allocation works, a deep dive into pointers is needed, here is a link that visually explains it well.
In Conclusion
Understanding the difference between primitive and reference values can be simultaneously difficult and easy to understand. The further down you travel into the rabbit hole of memory management, the more you will begin to appreciate the engineering of smart memory management. But for now, all you need to know is that, in JavaScript and most other languages, primitive types are data structures that are immutable and stored in the memory region known as the stack. References are objects that are stored in the memory region known as the heap.