Can I handle an "undefined" case in a switch statement in JavaScript?

JavascriptSwitch Statement

Javascript Problem Overview


If I'm passing an object to a case statement, and there is a case where it is undefined, can I handle that case? If so then how? If its not possible, then what is the best practice for handling an undefined case for a switch?

Javascript Solutions


Solution 1 - Javascript

Add a case for undefined.

case undefined:
  // code
  break;

Or, if all other options are exhausted, use the default.

default:
  // code
  break;

Note: To avoid errors, the variable supplied to switch has to be declared but can have an undefined value. Reference this fiddle and read more about defined and undefined variables in JavaScript.

Solution 2 - Javascript

Well, the most portable way would be to define a new variable undefined in your closure, that way you can completely avoid the case when someone does undefined = 1; somewhere in the code base (as a global var), which would completely bork most of the implementations here.

(function() {
    var foo;
    var undefined;

    switch (foo) {
        case 1:
            //something
            break;
        case 2:
            //something
            break;
        case undefined:
            // Something else!
            break;
        default:
            // Default condition
    }
})();

By explicitly declaring the variable, you prevent integration issues where you depend upon the global state of the undefined variable...

Solution 3 - Javascript

If you're comparing object references, but the variable may not be assigned a value, it'll work like any other case to simply use undefined.

var obs = [    {},    {}];

var ob = obs[~~(Math.random() * (obs.length + 1))];

switch(ob) {
    case obs[0]: 
        alert(0); 
        break;
    case obs[1]:
        alert(1); 
        break;
    case undefined: 
        alert("Undefined"); 
        break;
    default: alert("some unknown value");
}

Solution 4 - Javascript

Since undefined really is just another value ('undefined' in window === true), you can check for that.

var foo;

switch( foo ) {
    case 1:
        console.log('1');
        break;
    case 2:
        console.log('2');
        break;
    case 3:
        console.log('3');
        break;
    case undefined:
        console.log('undefined');
        break;
}

works just about right.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionegucciarView Question on Stackoverflow
Solution 1 - JavascriptJason McCrearyView Answer on Stackoverflow
Solution 2 - JavascriptircmaxellView Answer on Stackoverflow
Solution 3 - JavascriptI Hate LazyView Answer on Stackoverflow
Solution 4 - JavascriptjAndyView Answer on Stackoverflow