JavaScript check if value is only undefined, null or false

151,694

Solution 1

Well, you can always "give up" :)

function b(val){
    return (val==null || val===false);
}

Solution 2

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.

Solution 3

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 ""
}

Solution 4

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.

Solution 5

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...
}
Share:
151,694
Lime
Author by

Lime

https://www.toptal.com/php/a-utf-8-primer-for-php-and-mysql https://gist.github.com/mwunsch/4710561 How does GitHub detect whether the browser has color emoji support? Detect emoji support - xpath CSS SQL https://pastebin.com/raw/8c9RJW70 https://stackoverflow.com/q/32981319 https://stackoverflow.com/q/15305852 Pass arguments to a scriptblock in powershell jQuery for java - jsoup gwtquery Development Environments - eclipse, netbeans, visual studio, intellij Call Java function from JavaScript over Android WebView How to open layout on button click (android) style & themes https://developer.android.com/reference/packages.html How can we view webpages in our android application without opening browser? http://www.ezzylearning.com/tutorial/customizing-android-listview-items-with-custom-arrayadapter Best way to reorder items in Android 4+ ListView In Android, how can I set the value of a edit box in WebView using Javascript What does WISC (stack) mean? How to create custom view from xml-layout? Create View-Object from XML file in android Java http://chat.stackoverflow.com/transcript/message/35730032#35730032 How do I "decompile" Java class files? Is there something like python's interactive REPL mode, but for Java? Is there a package manager for Java like easy_install for Python? Hyperpolymorph, Hyperpolyglot, https://certsimple.com/rosetta-stone Lisp | A Replace Function in Lisp That Duplicates Mathematica Functionality | Lisp Interpreter How to change XAMPP apache server port? xampp MySQL does not start http://es6-features.org/ react-native phonegap https://cordova.apache.org/ http://en.cppreference.com/w/c/types/integer ModernC autoit mouserecorder What are the maximum number of arguments in bash? Maximum number of Bash arguments != max num cp arguments? Maximum string length node.js and python? IE For Linux https://developer.mozilla.org/en/docs/Web/API/Touch_events JavaScript for detecting browser language preference

Updated on July 31, 2022

Comments

  • Lime
    Lime almost 2 years

    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.

  • Joseph Marikle
    Joseph Marikle almost 13 years
    @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 >.>
  • Rohan Desai
    Rohan Desai almost 13 years
    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.
  • Joseph Marikle
    Joseph Marikle almost 13 years
    @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 what
  • Felix Kling
    Felix Kling almost 13 years
    Some people consider this as bad style. The ternary operator should be used to return a value, not for it's side effects.
  • Lime
    Lime almost 13 years
    I would add functions where the false and true are then. Now it just appears as being over engineered.
  • Lime
    Lime almost 13 years
    Well I piratically gave up, but did end up changing false to !1
  • Konza
    Konza over 10 years
    I think we can change val === false to val == false :)
  • Rohan Desai
    Rohan Desai over 10 years
    @Konza: That just how == is defined. Its fairly complicated and its why many people recommend using === unless you really know what you are doing.
  • Sam
    Sam almost 10 years
    doesnot work better can be used as if(typeof variable_here === 'undefined'){ // your code here. };
  • Felix Kling
    Felix Kling about 8 years
    But that will also be true for 0 or "". Also, Yiding already provided this solution.
  • TOPKAT
    TOPKAT almost 8 years
    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 ?
  • Rohan Desai
    Rohan Desai almost 8 years
    thats strange. you might want to create a separate question thread for that.
  • Lime
    Lime over 7 years
    You forget 0 and ''
  • SudoPlz
    SudoPlz over 7 years
    Updated the answer to also take into account strings and the number zero 0.
  • Lime
    Lime over 5 years
    This techique is probably the best disregarding the NaN value.
  • JJS
    JJS over 3 years
    piratically - adv. do do something as pirate would...