Primitive and reference values in JavaScript

Primitive and reference values in JavaScript

"Primitive" and "reference" values in JavaScript, a concept most developers skip as it seems to be too theoretical, actually became quite important when I was learning React. If you don't know about this, let me quickly summarize the concept.

In JS, there are two types of data/values that can be stored in a variable, primitive value and reference value.

Q1. Which values are primitive and which ones are references?

  • Any number, string, boolean, undefined, null, or symbol is a primitive value.
  • Arrays, Objects, and Functions are reference values.

Q2. Where does a primitive value gets stored, and where does a reference value gets stored?

  • When you declare a variable having a primitive value, the JS engine allocates the memory and store the value on the stack.
  • On the other hand, when you declare a variable having a reference value, the JS engine allocates the memory and store the value on the heap.

Q3. On calling these two types of variables, what do we get in return?

  • When you access a primitive value, you get the actual value of it. That is why when we assign a variable that stores a primitive value to another, the value stored in the variable gets copied into the new variable. Now if you make a change in any of the variables, the other one doesn't get affected.
  • When you access a reference value, you get the reference/location of the memory of it. That is why when we assign a variable that stores a reference value to another, the location of the value is passed to the other variable. Now if you make a change in any of the variables, the other one also gets affected because they are pointing to the same value stored in the heap memory.

Want to read a more clear explanation with examples? You can check out an amazing article by Tyler McGinnis on the same.

Happy coding :)

#10DaysofJSfundamentals (Day 4)