Hi there Rain Lover,
if (document.getElementById('input').value === '0')
|JSLint error: "Expected '===' and instead saw '=='." |
|But when I ... change == to ===, the alert stops appearing. |
Are you asking why JSLint is suggesting this?
Yes, and if it's OK to just leave it as is:
input.value == 0
Sorry if the question wasn't very clear!
You're comparing a string value to an integer value. Accessing the value property of an input element will always return a string value:
The == operator will attempt to type-convert the values to do the comparison. The === operator will not, meaning if you try to compare a string with a number, it will ALWAYS return false. When you use == instead of === the string value type is converted to a number for the comparison.
As birdbrain suggested, changing 0 to '0' and using === will work. It's then comparing 2 string values. Another alternative would be to explicitly convert the value of the input field to a number first.
|As birdbrain suggested, changing 0 to '0' and using === will work. It's then comparing 2 string values. |
input.value == '0'?
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?
Yes, that's essentially the same thing without the type conversion (but JSLint will probably still complain about the ==). If you were going to do that, you might as well use the strict comparison operator instead.
While I haven't tested it, I suspect that yes, a comparison that doesn't need a type conversion would be faster. With that said, the difference would be so small (minuscule really) that it would not be noticeable unless you were looping over HUGE data (and I mean really huge), so there's no real performance gains to be had by using one or the other.
(EDIT: Didn't see Fotiman's post just above before posting this...)
|How about input.value == '0'? |
Yes, that is OK. (Comparing two known strings.) I don't see as there is any benefit to using the identity operator (===) in this instance. And JSLint is OK with this too.
|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? |
Well, yes... marginally... a micro optimisation at best. But it is not for performance that you would choose one over the other. It could depend on your program logic, on the data being entered. As Fotiman states, in the case of the (input.value == 0) comparison, the value (a string) is first converted to a number....
'0' == 0 [TRUE]
'00' == 0 [TRUE]
'0x0' == 0 [TRUE]
'0' == '0' [TRUE]
'00' == '0' [FALSE]
'0x0' == '0' [FALSE]
|Accessing the value property of an input element will always return a string value |
That's the key point. Thank you!
|I don't see as there is any benefit to using the identity operator (===) in this instance. |
That's what I thought although everyone recommends