Understanding Loose & Strict Equality Operators in JavaScript


In this javascript tutorial, we will learn about loose equality (== and !=) and strict equality (=== and !==) operator in javascript.

Many developers consider the loose equality operators (== and !=) to be evil, and discourage their use. The main reason why developers eschew loose equality operators is that they test primitive values rather than the variable object. For example, the following code succeeds:

let greet = new String('hello');
if (greet == 'hello') { ...}

whereas this code fails:

let greet = new String('hello');
if (greet === 'hello') { ...}

The first code snippet succeeds because the string literal (hello) and the primitive value the greet variable contains are identical. The second code snippet fails the conditional test because the objects being compared are not equivalent, though they both share the same primitive value (hello): the greet variable is a String object, while the compared value is a string literal. While results of this comparison are relatively intuitive, others are less so. In the following code snippet, a string is compared to a number, and the results may be unexpected:

let number = 20;
let string = '20';

console.log(number === string); // false
console.log(number == string); // true

So this was a quick overview on JavaScript loose and strict equality operator.

Leave a Reply

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