0

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!

crazy_in_love
  • 145
  • 3
  • 13

4 Answers4

2

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
Community
  • 1
  • 1
nicosantangelo
  • 13,216
  • 3
  • 33
  • 47
1

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1
""==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.

mpm
  • 20,148
  • 7
  • 50
  • 55
1

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.

Christoph
  • 50,121
  • 21
  • 99
  • 128