Javascript Primitives and Non-Primitives values

Javascript provides different data types to store values. There are two types of data types namely:

  • Primitive data type
  • Non-primitive data type

The primitive data types are as follows-

  1. String - "Hello"
  2. Number - 100
  3. Boolean - true/false
  4. Undefined - represents undefined
  5. Null - represents null
  6. BigInt - to store a large number beyond Number.MAX_SAFE_INTEGER
  7. Symbol - new addition in ES2015

The non-primitive data types are as follows-

  1. Objects
  2. Functions.
  3. Arrays - They come under objects.

Are the data types mutable or immutable?

All primitives are immutable. Meaning they cannot be altered but they can be reassigned to a new variable. So the point to be noted here is, a part of the existing value cannot be changed but the entire value can be reassigned.

So let us look at an example to get more understanding.

carbon (1).png

Also primitives are compared by value. Two values are equal if they have the same value

Lets look at an example

carbon (2).png

All non-primitive are mutable. They can be altered.

Consider the following example -

carbon (3).png

Non-primitives are compared by reference and not by values. So even if an array/object are assigned the same values, they are not equal.

But note that if we assign the same reference, then they are equal.

Look at the example to understand the same

carbon (4).png

Conclusion

  • All primitive data types are immutable whereas all non-primitive data types are mutable.
  • Primitive data types are compared by values and non-primitive data types are compared by reference.