4

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 :/

ousmane784
  • 306
  • 1
  • 17

4 Answers4

0

For type check you have:

typeOf: // note: typeof [] = object and typeof {} = object https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

Array.isArray(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray

isNaN()/Number.isNaN(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN

Is one of those what you're looking for?

!0 = true // in js. just tried it on MDN
0

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;
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
0

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))
twharmon
  • 4,153
  • 5
  • 22
  • 48
0

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));
dikuw
  • 1,134
  • 13
  • 22