4 ms·
Depending on your conventions for null/undefined (another annoying wart of JavaScript), I think it often makes sense to treat `== null` as a special allowed cas
by alangpierce 8y ago
Depending on your conventions for null/undefined (another annoying wart of JavaScript), I think it often makes sense to treat `== null` as a special allowed case. In the code I work in, `== null` is strongly encouraged (but not required) as the way of doing null checks, and all other uses of `==` are disallowed by lint. Just like our other patterns and conventions, it's something people pick up reasonably quickly as they're introduced to the code, nothing tricky, just a little pattern that acts as a concise replacement to the `?` operator from CoffeeScript.
The alternatives are writing `x === null || x === undefined` everywhere (which might lead to people just picking one out of laziness, leading to bugs), doing things like `if (x)` (which we still do sometimes, but can lead to subtle falsy-related bugs if you're not careful), or to do careful bookkeeping of when variables might be null vs undefined. In my opinion, the null/undefined distinction is more cognitive overhead than the benefit it provides, so it's best to just check for both at the same time and never intentionally treat them as different. Given that mindset, I think the `== null` pattern is slightly unfortunate, but better than the alternatives.
- novaleaf 8y agoexactly! `==null` and `!=null` are the only reasons I use it. For those not aware, you can specify a rule in [js/es/ts]lint to allow only these cases.
- Rumudiez 8y agoMy team checks for types, not for null. `const isString = myVar => typeof myVar !== 'string'` This is more reusable and more idiomatic in my opinion than null/undefined checks
- styfle 8y agoThis is especially useful if you are using TypeScript (or Flow I assume) because the type checker can give you an error at compile time. After performing the runtime check, TypeScript will know that null/undefined is not possible. See this example https://goo.gl/AyoC3T https://goo.gl/AyoC3T
- jscissr 8y agoBut then you have the problem that typeof null === 'object'.
- hibbelig 8y agoShouldn't that be called `isNotString`?