In this post, we will take a look at a super common interview question: primitive vs reference values in JavaScript.
What is a primitive value?
In JS, there are 6 primitive values: number, string, boolean, undefined, null and symbol.
You can think of them as the base, hence the name primitive. These values are not objects and they don't have methods.
What is a reference value?
The short answer is: anything that is not a primitive value is a reference value. They are typeof "object"
. We are talking about objects, arrays, functions, etc.
Key differences
The key difference is how these values behave under the hood. Specifically, how they store their values in memory.
The primitive values would have the value in memory, while the reference values would have a reference to that location in memory (the memory address), and not the value itself.
For example:
let name = 'Jesus'
let nickName = name
name = 'Juan'
console.log(name) // 'Juan'
console.log(nickName) // 'Jesus'
We are only using primitive values here, so everything makes sense. Right?
Now, let's take a look at a reference values example:
let jose = {
type: 'Person',
name: 'Jose'
}
let juan = jose
juan.name = 'Juan'
console.log(jose.name) // 'Juan'
console.log(juan.name) // 'Juan'
See? In here, the juan
variable is referencing the same spot in memory as the jose
variable. That is why when we change the name
property in one of them, we will be changing it in both.
This behavior also explains why if we compare two seemingly equal reference values, the result will be false
. For example:
const fruit = {
color: 'Yellow',
name: 'Banana'
}
const snack = {
color: 'Yellow',
name: 'Banana'
}
fruit === snack // false
So primitive types are compared by their value, while reference types are compared by their reference.
Lastly, remember that primitive values are immutable. So when you change a primitive value, what you are doing is replacing the in-memory value. You are not modifying it like you can do with reference values.
Top comments (0)