Do I need to check for null and length, or is there a shorter way to check for a non-empty string?

I set the value of the #thimble hidden field when the page loads using values ​​on the server side.

Then in JavaScript, I want to work on this value only if it was filled with some non-empty string.

Is this the shortest way to verify that a value is not empty?

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

Seems pretty long.

+6
javascript jquery string null
source share
3 answers

An empty string is false, I would not even bother to check its length .

The following is an example:

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

False is a value that expresses false when evaluated in a boolean context (for example, the condition of an if ).

Falsey Values:

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

Remember that a string in a boolean context creates false only when its length is 0 , if it has a space, it creates true anyway:

 Boolean(""); // false Boolean(" "); // true, whitespace 
+11
source share

If for $.trim - .length you mean everything except zero length or space, use $.trim with .length

 if ($.trim($("#thimble").val()).length) { ... } 
+3
source share
 if ($("#thimble").val().length) { carryOn(); } 
0
source share

All Articles