If the intent is to verify that the string is empty , then yes impairs code reading and possibly implementation. The reason is that the comparison made in:
if (!value) {
console.log("String vazia");
}
is not a check if the string is empty, but rather if the value of value
is falsy , as commented in the question itself. This implies that value
, besides can not be an empty string , can not be the integer zero, false, null, undefined, NaN not a number etc. However, all these values would be expected to pass the "not an empty " test because they are not, in fact, an empty string (except the string empty itself). When I do if (!value)
, it should be understood that value
can be any truthy value and not just a nonempty string .
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 that value
is an empty string , you will have to check the type of the variable, either using 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 is explicit that it is really desired to search for empty strings, so all other values are valid.
That is, using the hard comparison, with the ===
operator, since ==
makes a loose comparison.
What is 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 your goal.
It's very important to note that null is different from empty string . The Maniero's answer on this graphically shows the difference.