gtap-dev / javascript

JavaScript Style Guide
MIT License
0 stars 0 forks source link

15.3 - allow condition shortcuts for strings and numbers? #11

Open mjomble opened 3 years ago

mjomble commented 3 years ago

If there's any chance that the value may be null or undefined instead of a valid string, if (name) can't be safely converted to if (name !== '').

Instead you'd need to write if (name !== '' && name !== null && name !== undefined). To be completely safe in less familiar code, you might want to cover other falsy cases as well, such as NaN and 0.

So unless you can be absolutely sure that the value is always a string, if (name) seems more reliable and in my opinion, should be allowed. It should also be noted that even if TypeScript seems to guarantee that a variable will never be null or undefined, it can still sometimes happen if there's an inaccurate typedef somewhere, especially when using 3rd party libraries.


The same doesn't apply to number comparisons, because > 0 is false with all falsy values. But ideally I'd like to continue using this shortcut as well, because... I'm too lazy 😄

This may seem inconsistent with my suggestion in #10, but in this case the shortcut doesn't feel hacky or less readable to me. Although I suppose this may not be the case for people less familiar with how numbers behave in JavaScript. So I'm fine with disallowing the shortcut for numbers if others feel strongly about this.

mihkeleidast commented 3 years ago

Basically agree - looking at how I write code, I never want to explicitly check if my optional prop is undefined as well.

Additionally, the array length check seems unnecessary as well. A more important point IMO is to actually check array lengths, not just array existence.

mjomble commented 3 years ago

A more important point IMO is to actually check array lengths, not just array existence.

We could add an example that checks both using optional chaining syntax: if (array?.length) { ...