mortensen
mortensen

Reputation: 1237

Check if falsy except zero in JavaScript

I am checking if a value is not falsy with

if (value) {
  ..
}

but I do want to accept zeros as a (non-falsy) value. How is this normally done? Would it be

if (value || value === 0) {
  ..
}

or what?

Upvotes: 66

Views: 42162

Answers (4)

Steven Spungin
Steven Spungin

Reputation: 29091

For answer completeness, you can also just check for the other falsey values.

if (value !== false && value !== undefined && value !== null && value !== '') {

}

You can even check for a number to catch the zero, besides your example of checking for zero itself

if (!isNAN(value) || value) {
} 

Your example is the most succinct though, and also requires the least amount of processing.

if (value === 0 || value) {
} 

Upvotes: 3

SridharKritha
SridharKritha

Reputation: 9611

3 frequently useful condition checks:

  1. Filters all falsy [ 0, null, undefined, NaN, empty, string (""), false ]

    if(!value) 
    {
      // some non-falsy value
    }
    
  2. checks if the value is exist and also defined

    if(typeof value!== 'undefined') 
    {
      // value is exist and also defined
    }
    
  3. checks all falsy - except value 0

    if (value || value === 0) 
    {
      ....
    }
    

Upvotes: 8

vinayakj
vinayakj

Reputation: 5681

if (value || value === 0) {
  ..
}

is cleaner way, no problem.

Just for fun try this

val = 0;
if(val){
console.log(val)
}
//outputs 0   **update - it used to be.. but now it seems it doesnt in chrome

And

var val = 0;
if(val){
console.log(val)
}
//outputs nothing

Upvotes: 71

RK.
RK.

Reputation: 887

I would use value || value === 0. It's fine whichever way you do it but IMO this is the cleanest option.

Upvotes: 19

Related Questions