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