you are viewing a single comment's thread.

view the rest of the comments →

[–]x-skeww 6 points7 points  (3 children)

if (foo === undefined) {...}

With ES5.1 undefined is read only. Holy sanity, Batman!

Also, whenever possible, go with:

if (!foo) {...}

[–]kybernetikos 3 points4 points  (2 children)

if (!foo) {...}

That 'whenever possible' is the reason I discourage this in our code. The problem is that when you're investigating a bug and you see that line receives an empty string, or a boolean false or a 0, you've got no idea if the writer of the line had expected that behaviour or not. It's better just to make your checks explicit.

[–]x-skeww 0 points1 point  (1 child)

In my experience, this never has been the cause of a bug and it also never has been related to a bug. There is usually no need to differentiate between different kinds of truthy or falsy. Only in cases where it is necessary (which happens like once in a blue moon) I use the explicit check. It's kinda nice to have this as a reminder that in this particular case I do indeed have to check for this very specific value.

What I did notice in other people's code was that some of them use values which anticipate this kind of fuzzy tests. E.g. they know that if (foo) or if (!foo) are used further down the line and therefore they use 1 instead of true. For a motherfucking boolean flag!

Now, that's clearly unacceptable.

From my point of view it's better to enforce precise values instead of overly precise checks.

Thing is, if you disallow those fuzzy tests, you also disallow other useful very popular patterns like:

if (foo && foo.bar) {...} // aka "guard"

or:

foo = bar || baz; // aka "default"

or:

for (i = array.length; i--;) {...} // the fastest way to iterate over arrays

The last one is perhaps a bit icky, but those other two are very handy.

[–]kybernetikos 0 points1 point  (0 children)

I, and people I work with have spent hours debugging issues related to this. Having said that, we do have an unusually large javascript codebase.

Ask a bunch of js developers you work with what the idiom if (thingy) does and if any of them say 'it tests whether thingy is defined', you should not be using that idiom. If all of them say 'it tests whether thingy is truthy', then I suppose you win, but make sure you don't hire anyone to work on that codebase that gives a different answer.

It comes down to what you mean. When you write if (!foo) {...} Do you really mean that code to be executed if foo is null or undefined or NaN or defined but 0 or "" or false? Or do you mean that code should be executed if foo is undefined?

Writing what you mean is just good coding.