Equality Operators

What is equality operators?

Equality operators comparing two values which will either return a Boolean value “true” or “false”.

Equality is use in decision making scenario. There’s two type of equality == “loose equality” & === “strict equality”. Why is this important? Because in a situation when I want to compare an object and primitive data, these two does the same thing, but the result are different.

Loose equality will try convert value to match each other data type before compare the value.

console.log(1 == "1");
console.log('hello' == 'hello');

// output: 

Strict equality does not do that, all it does is compare and considers operands of different type to be different, it’s also faster since it skip one step.

console.log(1 === "1");
console.log('hello' === 'hello');


So Which to use? Unless there is a good reason to use == It is widely consider best practice to use ===. So now I know what to use, I will stick to strict equality. Let see how strict equality compare primitive and object.

When comparing object and primitive, in primitive- strict equality just comparing the actual value, whether it’s a string, number, or Boolean.


var obj1 = 1
var obj2 = 1
console.log(obj1 === obj2);

//output: true

While an object, it doesn’t just look at the value in object but also in memory.

//object comparison

obj1 = {number: 1}
obj2 = {number: 1}
console.log(obj1 === obj2);

//output: false

The only time an object is equal to another object is when they are both the same.

let a = {number: 1};
let b = a;

console.log( a === b);

//output: true


Opposite of equality operators is Inequality operator !==. Strict inequality operator check if two operands are not equal and return Boolean. Similar to strict equality strict inequality also consider operands of different type to be different. To not confuse myself since it is best practice to use strict equality, I will only use strict inequality when comparing if two operands are different.

console.log(1 !== "1");
console.log('hello' !== 'hello');
console.log(true !== 1);


And that is my understanding on equality.

Array Methods Next!

My other post:
Control Flow
Logical Operators

Thanks for reading! 🙂

Source: DEV Community

November 28, 2021
Category : News
Tags: beginners | javascript | programming | webdev

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.