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

Can I handle an "undefined" case in a switch statement in 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.


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...


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