Using Triple Equals Operator in JavaScript

As we know, when we want to check for two equal values in JavaScript we use an "if"statement with a double equals operator (==).
And this equivalence check is a very important thing in any programming language.

Example:

If(a == b)
{
    //Do something;
}

But I saw some weird behavior when checking for equality in a condition. I had two functions of which the first function was returning an integer value while the other function was returning a string value. One function was returning 123 while the other returned "123".

function Func1()

{

        /Write some logic

        return 123;

}

 

function Func2()

{

        //Write some logic

        return ‘123’;

}

I checked the value of both functions using an if statement with a double equals operator and surprisingly it returned true.

Example

if (Func() == Func())
{
    alert(‘Both are equal’);
}
else
{
    alert(‘Both are different’);
}

Output: Both are equal

After research, I came to understand that the condition using the Double-Equals Operator was checking for values after converting the value to a specific type by the browser. As you all know, there are various types available in JavaScript like Number, Boolean, String, and Objects. If you do a comparison between numbers in string format (for example "123") with the actual integer value (for example 123) then the browser will convert the number in string format to the actual integer before comparison. And the output will be "Both are equal". How to solve this?

Then I came across with Triple Equal Operator (===) that is also called as strict equals

This operator checks for actual values without converting the type before comparison. So if we consider the same example then the output will be "Both are different". So I would recommend you to use Triple Equals Operator (===) instead of Double Equals Operator (==) since there would be an actual value comparison instead of forcefully trying and converting the type and doing the comparison.

Example

if (Func() === Func())
{
    alert(‘Both are equal’);
}
else
{
    alert(‘Both are different’);
}

Output: Both are different

The same rule apply to the not equal operator (!=) too. It will try to convert the value before comparison.

And if you use (!==) then type conversion is skipped and the value is actually checked for the != condition.

Some more surprise results which I observed in JavaScript are given below:

if (1 == true) //Output: true

if('' == 0) //Output: true

Where as:
 
if (1 === true) //Output: false

if('' === 0) //Output: false
 
Conclusion
Use of the Triple Operator is more beneficial than using the Double Operator when comparing two values.
I hope you liked this article. Don't forget to share your comment whether it's good or bad. Sharing is valuable no matter what.

Up Next
    Ebook Download
    View all
    Learn
    View all