Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do you have to check for null & length or is there a shorter way to verify a non-empty string?

I set the value of a hidden field #thimble on page load using server-side values.

Then in JavaScript I want to act on that value only if it has been populated with some non-empty string.

Is this the most concise way of checking that the value is non-empty?

if ($("#thimble").val() != null && $("#thimble").val().length > 0) {
    carryOn();
}

Seems rather long.

like image 235
Billy G. Avatar asked Nov 23 '10 01:11

Billy G.


1 Answers

An empty string is a falsey value, I wouldn't even bother to check its length.

The following is equivalent to your example:

if ($("#thimble").val()) {
    carryOn();
}

A falsey value is a value that produces false when evaluated in Boolean context (such as the condition of an if statement).

Falsey values are:

  • null
  • undefined
  • NaN
  • 0
  • "" (empty string)
  • false

Remember that a string in Boolean context produces false only when its length is 0, if it has whitespace it still produce true:

Boolean("");     // false
Boolean("    "); // true, whitespace
like image 72
Christian C. Salvadó Avatar answered Sep 18 '22 23:09

Christian C. Salvadó