Haseeb Asif
Haseeb Asif

Reputation: 1786

Javascript Optimal way of checking false statement except zero

In javascript we use shortand notation if(input){} to check for empty or null input. We will get false for Null, Undefined, false, 0, NAN, "". My requirements is that I want to get true for any number including zero so I have created a method as follows

function checkFalseExceptZero(value){

    if( value !== undefined && value !== null && value !== false && value !== "" && value.length !== 0 ) return true;
    else return false;
}

I have added all possible checks in the above method to get the desired result. I am curious if there is any quick, sweet, short or more robust approach to achieve the same?

Upvotes: 1

Views: 3436

Answers (3)

Me.Name
Me.Name

Reputation: 12544

For any valid number, including 0, JavaScript already exposes the isFinite function. This returns false for all non-numbers, as well as for infinite and NaN

Examples (excerpt from the linked mdn page):

isFinite(Infinity);  // false
isFinite(NaN);       // false
isFinite(-Infinity); // false

isFinite(0);         // true
isFinite(2e64);      // true


isFinite("0");       // true, would've been false with the 
                     // more robust Number.isFinite("0")

Upvotes: 1

Daniel Cheung
Daniel Cheung

Reputation: 4819

A simple to understand answer. The three equal signs in JS will not convert type to check if the values equal unlike the two equal signs.

0 == false //true
0 === false //false, because 0 is a number and false is a boolean

Therefore, the answer, if you want to put it inside a function:

JS:

function isNumber(v) {
    return typeof v === "number"
}

The function will check the type of the variable. So it is not actually comparing the value to determine the result. The function will only return true if the type of the variable is called number.

Test runs:

isNumber(0) //true
isNumber(false) //false
isNumber("0") //false
isNumber(undefined) //false

In case you want to know, typeof variable will return a string.

Upvotes: 3

Giuseppe Pes
Giuseppe Pes

Reputation: 7912

My requirements is that I want to get true for any number including zero so I have created a method as follows

function checkFalseExceptZero(value){
 if ( variable.constructor === Array) return !!value.length;
 return value === 0 || !!value;
}

This a shorter version of your function. This returns true only when value is 0 or a trully value. So :

checkFalseExceptZero(null) ==>  false;
checkFalseExceptZero(undefined) ==>  false;
checkFalseExceptZero(false) ==>  false;
checkFalseExceptZero("") ==>  false;
checkFalseExceptZero(0) ==>  true;
checkFalseExceptZero([]) ==>  false;
checkFalseExcpetZero([1]) ==> true;

Upvotes: 2

Related Questions