简体   繁体   中英

Javascript check >= 0 not null or undefined or ''

What is the most convenient / performant way to check if a variable is greater than or equal to 0 and not null or undefined or '' ? eg [0, Infinity) . Let's say my variable is x , the obvious x >= 0 doesn't work as null >= 0 is true . The best I could come up with was.

x > 0 || x === 0

Can anyone think of a better one?

It seems like this question should already exist so if someone can find this question I'm happy to delete mine.

Perhaps not the answer you're looking for but why not check for number first?

if (typeof x === "number" && x >= 0) {
  // Excludes non-number values such as null and undefined
}

Note that this will allow Infinity , if you want finite numbers only:

if (typeof x === "number" && isFinite(x) && x >= 0) {
  // ...
}

The number type check clarifies your intent .

Any attempt to make it short and smart will most likely rely on type coercion which is risky, complicated (not everybody is familiar with JS quirks) and unnecessary from a performance point of view.

Try this:

if (x != null && x >= 0)
{
    //then insert the code to be executed here
}

The not null call could be as follows

value !== null

And i think you should just keep the above zero check your already doing!

You could check for zero directly and omit falsy values for the second check.

x === 0 || !x && x > 0
-------                    only zero
           --              no other falsy values
                 -----     a non falsy value which is greater then zero

You can just check if the variable has a truthy value or not. That means

if( value ) { } will evaluate to true if value is not:

null undefined NaN empty string ("") 0 false The above list represents all possible falsy values in ECMA-/Javascript. Find it in the specification at the ToBoolean section.

Further read: http://typeofnan.blogspot.com/2011/01/typeof-is-fast.html

Use non-strict comparison with null and then compare numbers:

 function check(x) { return x != null && 0 <= x; } console.log(check(1), true); console.log(check(0), true); console.log(check(-1), false); console.log(check(null), false); console.log(check(undefined), false); console.log(check('1'), true); console.log(check('0'), true); console.log(check('Hello'), false); console.log(check('-1 and 2 and 3'), false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM