If the intention is really check whether the string is empty, then, yes, impairs the reading of the code and possibly the execution of it. The reason is that the comparison made in:
if (!value) {
console.log("String vazia");
}
is not a check whether the string is empty, but yes if the value of value
is falsy, as commented in the question itself. This implies that value
, not to be a string empty, cannot be the integer zero, false, null, undefined, Nan (not a number), etc. However, all these values would be expected to pass the test "it is not a string "because they are not, in fact, a string empty (except the string empty proper). When I do if (!value)
, it is understood that value
can be any value Truthy and not just one string unoccupied.
const testes = ["", false, null, undefined, NaN, [], 0, "Foo"];
for (let teste of testes) {
if (!teste) {
console.log("String vazia: " + teste);
} else {
console.log("Não é uma string vazia: " + teste);
}
}
To actually check whether value
is a string empty, you will have to check the type of the variable, whether using the typeof
:
const testes = ["", false, null, undefined, NaN, [], 0, "Foo"];
for (let teste of testes) {
if (typeof teste === "string" && teste.length == 0) {
console.log("String vazia: " + teste);
} else {
console.log("Não é uma string vazia: " + teste);
}
}
Note that when checking the type it becomes explicit that the desired is actually to search for strings empty, so all other values are valid.
That is to say using the rigid comparison with the operator ===
, since ==
makes a loose comparison.
What’s a loose comparison?
const testes = ["", false, null, undefined, NaN, [], 0, "Foo"];
for (let teste of testes) {
if (teste === "") {
console.log("String vazia: " + teste);
} else {
console.log("Não é uma string vazia: " + teste);
}
}
Again the check becomes explicit about its objective.
It is very important to point out that null is different from string empty. To maniero’s response about it shows graphically the difference.
I believe it can impair readability because the check is not exactly if it is not a string empty, but yes if the value is falsy, as well commented, then reading is not exact for those who know how the dynamic typing language works. For example, if
value
for 2, theif
will be false, even if it is not a string empty. Remembering that Javascript has the loose comparison, the verification of string would be emptyif (value === "")
. If it impairs reading, it is due to condition not doing exactly as described. It makes sense?– Woss