Checking whether a string is empty in Javascript. Idiomatic or readable?

Asked

Viewed 1,623 times

2

I understand that it is often best to value the readability and clarity of the code by programming explicit. This does not only stop the Javascript, also the C#, Python and perhaps the rest of the programming languages.

I know these conventions are not rules, but they help in the development process if they are chosen at the right time, in the right environment and in the right way.

In Javascript to test whether a string is empty or not, you can use:

const value = '';
if(!value) {
    console.log('String vazia!');
}

This is because the empty string is a value defined as falsy (documentation). And in addition to comparing value with "", he compares with null and various other values.

Although it works, does this form not impair readability? It is not clear to a C# or Java developer that this if is the condition of an empty string.

In this case, explicitly comparing would harm an idiomatic Javascript code, why?

  • 1

    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, the if will be false, even if it is not a string empty. Remembering that Javascript has the loose comparison, the verification of string would be empty if (value === ""). If it impairs reading, it is due to condition not doing exactly as described. It makes sense?

2 answers

8


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.

  • 1

    (+1) It would no longer be semantic to check .length == 0 who cast a cast for Boolean? that is to say if (typeof teste === "string" && teste.length === 0) {

  • 1

    @Sergio sure would. Good observation. I make the change as soon as possible.

1

You can use the class String to start a new variable of this type, see:

const myText = new String("Hello!");
console.log(myText.length); // Saída: 6 (tipo número)

const emptyText = new String("");
console.log(emptyText.length); // Saída: 0 (tipo número)

You can check the compatibility of this feature on MDN website

  • 2

    But the question is not about how to do it, but whether it harms the code in any way. It failed to say whether it harms or not and why.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.