RSS

Values regarded as conditional false in Javascript

13 Sep

These values are treated as false in conditional statements, all other values including the string ‘false’ are treated as true:

Value Type
0 Number
NaN Number
”(empty string) String
false Boolean
null Object
undefined Undefined

For example, the code below will alert “NaN is falsy”:

if (NaN) {    // false
    alert("NaN is truthy");
}

if (!NaN) {   // true
    alert("NaN is falsy");
}

But these values are not equal to Boolean false, for example:

if (NaN === false)    // false

Also always use equality operators === and !== instead of == and !=. The former ones make sure operands are of same type and same value. The later ones produce complicated results for operands of different types.

Since ”(empty string) is treated as false, we could check for empty input like this: jQuery detect if textarea is empty

Reference: JavaScript: The Good Parts

Advertisements
 
Leave a comment

Posted by on September 13, 2012 in Javascript, jQuery

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: