Comparison with 0 and JSLint error

Here’s the code:

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

DEMO

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…

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

coothead

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.

E.g.

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.

However:

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 ==

http://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript-comparisons

http://www.2ality.com/2011/12/strict-equality-exemptions.html

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).