Member-only story
Primitives vs. Reference Types: Bugs from Hell
Primitives and Reference Types are two distinct methods of how variables are stored in memory. Sometimes its a reference to where they’re stored in memory (like a location) and sometimes they’re stored as a value.
This distinction in data types leads to difficult bugs because if you don’t know this distinction exists, the bug is completely hidden. The logic will be cogent, but how the logic is executed by JS will continue to be hidden.
Primitive types are: String, Number, Boolean, undefined, null, and symbol
Reference types are: Array, Object, and Functions
The difference is minute, but can be exposed as such:
Primitives store the actual value in the variable.
let x = 1
let y = x
y = 6
console.log(x) // 1
console.log(y) // 6
Here we can see that on line 2,y is equal to x. This is not actually saying that y is equal to x, but rather it is equal to the value of x (in this case, 1). So when the value of y is updated, it is not updating x’s value because the reference was only ever to x’s value, not x itself.
This is completely different with Reference Types. As the name suggests, we are no longer dealing with values, but references to the data instead.
x = {value: 1}
y = x
y.value = 6
console.log(x.value) //6
console.log(y.value) //6