Other than creating a function, is there a shorter way to check if a value is undefined
,null
or false
only in JavaScript?
The below if statement is equivalent to if(val===null && val===undefined val===false)
The code works fine, I'm looking for a shorter equivalent.
if(val==null || val===false){
;
}
Above val==null
evaluates to true both when val=undefined
or val=null
.
I was thinking maybe using bitwise operators, or some other trickery.
Try like Below
Refer node-boolify
only shortcut for something like this that I know of is
The best way to do it I think is:
This will be true if val is false, NaN, or undefined.
I think what you're looking for is
!!val==false
which can be turned to!val
(even shorter):You see:
That works by flipping the value by using the
!
operator.If you flip
null
once for example like so :If you flip it twice like so :
Same with
undefined
orfalse
.Your code:
would then become:
That would work for all cases even when there's a string but it's length is zero. Now if you want it to also work for the number 0 (which would become
false
if it was double flipped) then your if would become:Boolean(val) === false. This worked for me to check if value was falsely.
Another solution:
Based on the document, Boolean object will return true if the value is not 0, undefined, null, etc. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean
So