Comparison with 0 and JSLint error

Here’s the code:

<input type="number" value="0" id="input">
  if (document.getElementById('input').value == 0) {
    alert('Hello, world!');


And here’s the JSLint error:

Expected ‘===’ and instead saw ‘==’.

But when I listen to the advice and change == to ===, the alert stops appearing.

Hi there Rain Lover,

JSLint requires…

if (document.getElementById('input').value === '0') [/color]


Just to expand on what coothead says, the tipple equals is also called the “strict equals” operator.
It never does type coercion, so whenever you use it, you are ensuring the values are also of the same type.


var a = “0”; // a is a String
console.log(a == 0);
> true

The double equals operator converts the string into a number before doing the comparison.


var a = “0”; // a is a String
console.log(a === 0);
> false

No type coercion takes place and false is returned, as a String is not equal to a Number.

There are enough articles on why it is a good idea to use === and not ==

But to boil it down “Less magic in your code usually means that it is easier to understand”.

Thanks for the explanation and references!

Then am I right in my assumption that input.value == ‘0’ is faster than input.value == 0 as the first one doesn’t need a conversion?

Hmmm. I wouldn’t worry about speed here.

Simply put, do this:

input.value === '0'

(and read the 2ality article if you have time).