I'm checking JavaScript code based on JSHint tool. This tool detected lots of errors about using "===" instead of "==". My question is that Is it safe to just follow what JSHint said? Do I need to check further (about their types and values) before replacing == by === ? Thanks!
-
1You may need to check, yes. – powerbuoy Apr 09 '13 at 11:48
4 Answers
Yup, you should.
If you wrote your code without having into account type coercion some errors you didn't expect could happen, like
'' == '0' // false
0 == '' // true
0 == '0' // true
false == 'false' // false
false == '0' // true
false == undefined // false
false == null // false
null == undefined // true
' \t\r\n ' == 0 // true

- 1
- 1

- 13,216
- 3
- 33
- 47
My question is that Is it safe to just follow what JSHint said?
No. You might be depending on the type coercion that ==
gives.
Do I need to check further (about their types and values) before replacing == by === ?
Yes.

- 914,110
- 126
- 1,211
- 1,335
""==0 // true
""===0 // false
so you cant just blindly change all your code and expect it to work like before. That's why your code should have unit tests. So you know what doesnt work anymore.

- 20,148
- 7
- 50
- 55
-
According to Douglas Crockford (quoted without attribution by @Nicosunshine), `""==0` is `false`... – Tim Pietzcker Apr 09 '13 at 12:09
-
@TimPietzcker I left the link to the answer where I copied the info :). Maybe I should have made it more clear, my bad – nicosantangelo Apr 09 '13 at 13:19
Replacing ==
by ===
is a recommendation because it makes the code easier to predict and less error prone. Douglas Crockford proposes to never use ==
. However it is just his opinion.
Actually, if you have such checks in your code and know what you are doing (that the types will get coerced) and perhaps are even relying on that behaviour, it is absolutely okay to work with those comparisons. You can just uncheck the "Warning about unsafe comparison".
If you want to replace those comparisons you definitely have to check if your code keeps working as intended.

- 50,121
- 21
- 99
- 128