Do you see people as objects? A tale about primitive and non-primitive data types.

Do you see people as objects? A tale about primitive and non-primitive data types.

Have you ever used the equality operator? The one which returns true/false based on if two values are equal or not. Javascript has two types of equality operators, loose equality operator(==) and another is strict equality operator (===). As the name suggests, the strict one is more restrictive about data types but loose one doesn't care much about anything except values.

With this knowledge, let's try to solve some basic queries...

// What will be the output of this program?

const a = 5;
const b = 5;

if ( a == b ){
    console.log("a and b are both equal according to loose equality checking.");
}

As you have guessed rightly, the output is a and b are both equal according to loose equality checking., let us move to the next exercise...

// What will be the output of this program?

const people = { a : 1, b : 2 }
const person = { a : 1, b : 2 }

console.log(people == person)

With no intention to objectify people or people, we'll move for our output. The output of this program should be false.

Was it different from what you expected?

Let's discuss why it is what it is.

If you look for Data Types on MDN(Mozilla Developer Network), There are majorly two things mentioned, Primitive Data types and Non-Primitive Data types(written as Objects on the page). The list of primitive data types includes string, number, bigInt, etc( see full list here ), Whereas the non-primitive category includes an object or something which has methods.

In javascript, Objects are mutable hence we can modify their values(key-value pairs) even if they are assigned as const variables. However, unlike objects, primitive data types are immutable, which means we can not modify them.

We get the output of our question as false because, in JS, non-primitive data types always refer to address instead of values they hold. So in the case of our question, people and person both hold a reference to the address, which in both is different, as a result, when compared, they give output as false.

That was it for today. If you've read till last, you are awesome :)