JavaScript check if value is only undefined, null or false
Asked Answered
A

9

54

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.

Aldana answered 26/7, 2011 at 21:31 Comment(16)
What's wrong with: if (val){} ?Rosetterosewall
'',0,'0' and well several other configurations are trueAldana
if (val) // null undefined false or 0Pavel
The === operator works great here, why are you using == when comparing to null?Behlau
I think you meant if(!val). In that case '',0,'0' and well several other values are false.Aldana
it also satisfies undefinedAldana
If you use val === null and add val === undefined it should work fineTelephonic
Writing val==null is equivalent to writing val===null && val===undefined. I'm trying to get a shorter syntax.Aldana
val === null and val === undefined are different - you will not get true for val === null if val is undefined.Iman
@Iman null==undefined is true. val==null is true both when val is undefined or nullAldana
I think this is the shortest you can get... or create your own function. Btw, '0' does not evaluate to false.Sadonia
@Aldana - give er' a whirl - lemme know what the prompt says... alert(null === undefined ? "Yep" : "Nope");Iman
@Felix Thanks for the correction. @Brian Did you read my comment or question? I have always posted == not ===. give this a whirl :D alert(null == undefined ? "Yep" : "Nope");Aldana
@Aldana - gotcha - I think the shortest you'll get here is if(val === undefined || !val), and that's going to count zeros as false, which I don't think you want...Iman
This is a bit of a mess. If you arrive here like I did, just go read this: mapbender.org/JavaScript_pitfalls:_null,_false,_undefined,_NaNLiaison
What's wrong with if (!value) ?Junto
W
41

Well, you can always "give up" :)

function b(val){
    return (val==null || val===false);
}
Wether answered 26/7, 2011 at 22:4 Comment(7)
Well I piratically gave up, but did end up changing false to !1Aldana
I think we can change val === false to val == false :)Kerrykersey
@Konza: That just how == is defined. Its fairly complicated and its why many people recommend using === unless you really know what you are doing.Wether
doesnot work better can be used as if(typeof variable_here === 'undefined'){ // your code here. };Lacunar
It's crazy but for me it doesn't worw with null but with 'null' !! And also not work with val == '' (tested both in firefox console and live....if you have a clue ?Withdraw
thats strange. you might want to create a separate question thread for that.Wether
piratically - adv. do do something as pirate would...Richthofen
H
20

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 ""
}
Hufnagel answered 29/12, 2016 at 17:22 Comment(2)
You forget 0 and ''Aldana
Updated the answer to also take into account strings and the number zero 0.Hufnagel
C
19

The best way to do it I think is:

if(val != true){
//do something
} 

This will be true if val is false, NaN, or undefined.

Character answered 16/10, 2013 at 23:15 Comment(1)
This techique is probably the best disregarding the NaN value.Aldana
H
3

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

If value is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false.

So

if(Boolean(val))
{
//executable...
}
Health answered 17/12, 2015 at 21:44 Comment(0)
C
2

One way to do it is like that:

var acceptable = {"undefined": 1, "boolean": 1, "object": 1};

if(!val && acceptable[typeof val]){
  // ...
}

I think it minimizes the number of operations given your restrictions making the check fast.

Cumings answered 14/1, 2013 at 7:43 Comment(0)
E
1

only shortcut for something like this that I know of is

var val;
(val==null || val===false) ? false: true;
Excurvate answered 26/7, 2011 at 21:44 Comment(5)
@missingno can't see why not... it's shorter than writing out if ... else ... and in any case, how shorter can you get a conditional statement like this? ... better answer than "just give up" imo >.>Excurvate
All your conditional does is convert things to a boolean. However, this can be done much succintely with !! or, in this case, by doing nothing at all as the consition already is a boolean.Wether
@missingno no no no.... any code you want to execute based on the condition would go in place of the false and true... those are just there for clarity sake as to what results in whatExcurvate
Some people consider this as bad style. The ternary operator should be used to return a value, not for it's side effects.Sadonia
I would add functions where the false and true are then. Now it just appears as being over engineered.Aldana
A
1

Boolean(val) === false. This worked for me to check if value was falsely.

Amylum answered 12/3, 2016 at 18:0 Comment(1)
But that will also be true for 0 or "". Also, Yiding already provided this solution.Sadonia
Y
0

Using ? is much cleaner.

var ? function_if_exists() : function_if_doesnt_exist();
Yukyukaghir answered 30/6, 2016 at 9:33 Comment(0)
G
-1

Try like Below

var Boolify = require('node-boolify').Boolify;
if (!Boolify(val)) {
    //your instruction
}

Refer node-boolify

Glaive answered 8/1, 2019 at 10:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.