I think what you're looking for is !!val==false
which can be turned to !val
(even shorter):
You see:
function checkValue(value) {
console.log(!!value);
}
checkValue(); // false
checkValue(null); // false
checkValue(undefined); // false
checkValue(false); // false
checkValue(""); // false
checkValue(true); // true
checkValue({}); // true
checkValue("any string"); // true
That works by flipping the value by using the !
operator.
If you flip null
once for example like so :
console.log(!null) // that would output --> true
If you flip it twice like so :
console.log(!!null) // that would output --> false
Same with undefined
or false
.
Your code:
if(val==null || val===false){
;
}
would then become:
if(!val) {
;
}
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:
if(!val && val !== 0) {
// code runs only when val == null, undefined, false, or empty string ""
}
''
,0
,'0'
and well several other configurations are true – Aldana===
operator works great here, why are you using==
when comparing tonull
? – Behlauif(!val)
. In that case''
,0
,'0'
and well several other values arefalse
. – Aldanaundefined
– Aldanaval === null
and addval === undefined
it should work fine – Telephonicval==null
is equivalent to writingval===null && val===undefined
. I'm trying to get a shorter syntax. – Aldananull==undefined
is true.val==null
is true both when val isundefined
ornull
– Aldana'0'
does not evaluate tofalse
. – Sadonia==
not===
. give this a whirl :Dalert(null == undefined ? "Yep" : "Nope");
– Aldanaif (!value)
? – Junto