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?
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.
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.
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.
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With