4 ms·
Is === really necessary for Javascript? Type checking seems like overkill?
by nicetryguy 5y ago
Is === really necessary for Javascript? Type checking seems like overkill?
- kylemuir 5y agoDepends how much you care about the equality and how strict. by default == will do type coercion so you can get weird results where things like [] == 0 are true. More equality fun in JS can be seen here: https://dorey.github.io/JavaScript-Equality-Table/ https://dorey.github.io/JavaScript-Equality-Table/
- Arainach 5y agoYou should confirm that the inputs are what you expect them to be. There's almost no time when you shouldn't be checking the type.
- tlrobinson 5y agoIt’s a well known rule in JavaScript to default to “===“ for everything except checking for null or undefined, in which case “== null” is acceptable. https://eslint.org/docs/rules/eqeqeq#smart https://eslint.org/docs/rules/eqeqeq#smart Even better is to just use TypeScript.
- BigJono 5y agoChecking for 'null or undefined' is an antipattern anyway, so there's no real valid use of '=='.
- flippinburgers 5y agoDoes typescript really protect one from javascript though? I imagine it is fine. If it was just myself developing I would be fine, but the insufferable junior devs that learned "=== or die" rear their ugly heads.
- numlock86 5y agoIn best practice you should always use === unless you know exactly why you wouldn't for a specific case.
- pdpi 5y agoa == !a There’s several values of a where that yields true (of the top of my head, a = '0' is one of them). Yes, you do need ===.
- chx 5y agoIf someone doesn't understand this then here's why. You need to learn the Six Falsey Things In JavaScript. Everything else when cast to boolean will be true. These six things are What and Why and When And How And Where and Who. Wait, no, that's a totally different list of six... anyways false undefined null NaN 0 "" (empty string) That's it. Since '0' is neither when the negate operator casts it to boolean it'll become true. And then negating it becomes false. When doing a comparison between '0' and false, the standard says https://262.ecma-international.org/5.1/#sec-11.9.3 https://262.ecma-international.org/5.1/#sec-11.9.3 > If Type(y) is Boolean, return the result of the comparison x == ToNumber(y). ToNumber(false) is of course 0. So you are running '0' == 0 which is visibly true...
- pdpi 5y ago> So you are running '0' == 0 which is visibly true... Crucially, there's the extra step of converting '0' to a number.
- megous 5y agoIt's not, it's just one of the tools in the toolbox.