In this article you will see that How to handle an "undefined" case in a switch statement in JavaScript? Or Deal with undefined variable in Javascript switch case
In a switch
statement in JavaScript, you can handle the "undefined" case by using a default
case. The default
case is executed when none of the other cases match the switch expression. Here's an example:
let value = undefined;
switch(value) {
case 1:
console.log("Value is 1");
break;
case 2:
console.log("Value is 2");
break;
default:
console.log("Value is undefined");
}
In this example, if value
is undefined
, the default
case will be executed, and the message "Value is undefined" will be logged to the console.
You can also use an if
statement to handle the undefined case, like this:
let value = undefined;
if (typeof value === 'undefined') {
console.log("Value is undefined");
} else {
switch(value) {
case 1:
console.log("Value is 1");
break;
case 2:
console.log("Value is 2");
break;
default:
console.log("Value is something else");
}
}
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");
}
Since undefined
really is just another value ('undefined' in window === true
), you can check for that.
if (typeof value === 'undefined') {
console.log("Value is undefined");
} else {
console.log("Write your code");
}