DEV Community

Cover image for Reference VS. Primitive Values
SURAJITSHAW
SURAJITSHAW

Posted on

Reference VS. Primitive Values

Do you know there is two types of values in JavaScript ?

> primitive values and reference values.

You maybe know that but do you know what are the difference between those 2 types ? How they stores in memory ?

> if your answer is "no", not to worry, we are gonna discuss all this in details. Just keep reading this blog 😊

Image description
In ECMAScript 2015 we were introduced more two primitive data types. There's a saying Everything in JavaScript is a Object, well almost everything except Primitive data types.

Now let's see how Primitive values differs from Reference values :

Image description

If you come from different languages ( e.g : C/C#, Java ) you probably know the concept of 'PASS BY VALUE' & 'PASS BY REFERENCE'.

In simple terms...

"Passing by value"_ means that you pass the actual value of the variable into the function. So, in your example, it would pass the value 9._
"Passing by reference" means that you pass the variable itself into the function (not just the value). So, in your example, it would pass an integer object with the value of 9.

Image description

In JavaScript you can consider Primitives with Pass by value and Reference values with Passing by reference. Also in code snippet you can clearly show when change the value of obj1, changes are reflects to copied obj2 as well. But in case of primitives you just pass a copy of original value so after when you change the original it doesn't affect the copied value.

Primitives : We store the actual value.

Reference : Here variable store the address where the data in heap memory is located. This doesn't store the actual value like primitives, instead a pointer or a reference to data.


SUMMARY

PRIMITIVES VALUES :

  • Value types are immutable.
  • value types are compared by value.
  • value types are copied by value.

REFERANCE VALUES :

  • reference types are mutable.
  • reference values are copied by address to memory or reference.

If you find this blog helpful make sure to give it 💛, also can follow me on Twitter for more helpful resources and tips.

Top comments (0)