JavaScript check for value including 0

Viewed 280

In javascript I need to check for a value in an if statement if it exists. The thing is 0 can be one of the accepted values. so when I do

if(!val) {
   return true
}

return false

The thing is Javascript evaluates !0 = false

here are test cases what I want:

val = 0 // true
val = 91 // true
val = null // false
val = undefined = false

Basically check check for null but include 0. Not sure how to do this :/

4 Answers

I think you need to be checking for null & undefined in your conditional statement. That way, anything that is 0 or greater will return true. You also need to check the typeOf() for undefined because you undefined is not the value of the variable.

if (typeof(val) != 'undefined' && val != null && !(val < 0)){
    return true;
}else{
    return false;
}

Check for undefined and null:

function isValNumber(val) {
  if (val === undefined || val === null) {
    return false
  }
  return true
}

console.log(isValNumber(0))
console.log(isValNumber(91))
console.log(isValNumber(null))
console.log(isValNumber(undefined))

0 is falsy so !0 is true in JavaScript, but to meet your test cases I think you want truthy values to return true, and you need to handle the special case for 0. One way to do it:

function test(val) {
  if (val || val === 0) {
    return true
  }
  return false
}

console.log(test(0));
console.log(test(91));
console.log(test(null));
console.log(test(undefined));

You could also leverage Javascript's weak equivalence operator and use != null which covers null and undefined as below:

function test(val) {
  if (val != null) {
    return true
  }
  return false
}

console.log(test(0));
console.log(test(91));
console.log(test(null));
console.log(test(undefined));

Related