Hi everyone. In this post I want to point out a not so common way to compare variables and their values in JavaScript.

For many out there, the common way to compare 2 values is to use the == or != operators. If we look at the example below however, you’ll notice an interesting result that is returned:

Example:

var boolFalse = false;

var boolTrue = true;

var myString = “”;

if(boolFalse == 0) //This returns True

if(boolTrue == 1) //This returns True

if(myString == 0) //This returns True

The reason why these values are returning true is because as a default, when using == or !=, JavaScript only compares the values and not their variable types.

If you wanted to perform a strict comparison between 2 variables using their Value as well as Type, then you will need to use === or !==.

Example:

if(boolFalse === 0) //This returns False

if(boolTrue === 1) //This returns False

if(boolTrue !== 1) //This returns True

if(myString === 0) //This returns False

 

I now use this as a Standard when coding in JavaScript. I hope this makes sense.

Happy coding :)

John.

LinkedIn