Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 636
egucciar Avatar asked Oct 02 '12 18:10

egucciar


People also ask

What Cannot be used in a switch statement?

The switch/case statement in the c language is defined by the language specification to use an int value, so you can not use a float value. The value of the 'expression' in a switch-case statement must be an integer, char, short, long. Float and double are not allowed.

What will happen if the switch statement did not match any cases?

If the switch condition doesn't match any condition of the case and a default is not present, the program execution goes ahead, exiting from the switch without doing anything.

Can case in switch statement have conditions?

In a switch statement, we pass a variable holding a value in the statement. If the condition is matching to the value, the code under the condition is executed. The condition is represented by a keyword case, followed by the value which can be a character or an integer.

What if none of the cases match the value in switch-case statement?

The computer will go through the switch statement and check for strict equality === between the case and expression . If one of the cases matches the expression , then the code inside that case clause will execute. If none of the cases match the expression, then the default clause will be executed.


2 Answers

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.

like image 90
Jason McCreary Avatar answered Sep 17 '22 14:09

Jason McCreary


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

like image 25
ircmaxell Avatar answered Sep 16 '22 14:09

ircmaxell