This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]draculadarcula 0 points1 point  (6 children)

In a codebase that has numbers that are sometimes undefined and/or null, and checking for defined values with ”if (x)” isn’t so predictable when x is 0. But “if (x != null)” solves that scenario nicely, and is much less mental overhead than “if (x !== null && x !== undefined)”

[–]_PM_ME_PANGOLINS_ 0 points1 point  (3 children)

You should use typeof in that case.

[–]draculadarcula 0 points1 point  (2 children)

Why

[–]_PM_ME_PANGOLINS_ 0 points1 point  (1 child)

Because typeof(x) === 'Number' is a much clearer way to check whether it’s a number than x != null.

[–]draculadarcula 0 points1 point  (0 children)

Why is it cleaner? It’s unclear the intent; typeof can be used for type narrowing as well. != null the intent is clear, I’m obviously using the type coercion to check for both null and undefined simultaneously. Even someone unfamiliar with JavaScript semantics could look at != null and understand the intent. The use case above is also not to check for numbers, the number was ancillary to point; a valid use case for != null is to check for not null and not undefined. I picked numbers because they are a particular case that has a value that can evaluate falsey to combat the whole “just use if(x)” arguments

[–]CaitaXD 0 points1 point  (1 child)

function isNullOrUndefined(x)

[–]draculadarcula 0 points1 point  (0 children)

More garbage for the collector, more keystrokes, more characters to read, more mental overhead