Domanda

I saw many times in open source projects that folks write something like that:

if("" !== foo) {
    // ...
}

Why on earth do they do that? I mean you are checking if foo's value is empty string or not. I understand that "" !== foo and foo !== "" means exactly the same. But what's the reason to write tricky and less obvious code?

È stato utile?

Soluzione

I'm personally not a fan of this style, either; however, the style stems from this:

 if (x = "") { // **oops**, meant to do "==" but ended up assigning to "x"
    // ...
 }

The "if" statement here will cause an unintended side-effect. There are a number of languages in which side effects and implicit conversions to boolean make it easy to shoot oneself in the foot this way (JavaScript and C++ come to mind). To avoid this, some have the convention of inverting the ordering, since assigning to a constant will produce a more immediate and obvious error. I'm personally not a fan of this, because it makes the code read less like English ("if x equals the empty string" reads more naturally than "if empty string equals x"), and better tooling (linters, source code analyzers, etc.) can catch these just as effectively.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top