I have written the below code.
if(result === ""){
show("Something went wrong!!");
}
else if (result === "getID") {
show("success");
}
else {
doSomething();
}
How can I write this using a switch case statement in JavaScript. I'm not sure how can I check for a null value in a switch case condition.
Could someone help me on this??
You can do either of these: if (i == null) { // ... } else switch (i) { case 1: // ... break; default: // ... } if (i != null) switch (i) { case 1: // ... break; default: // ... } else { // ... }
Javascript null is a primitive type that has one value null. JavaScript uses the null value to represent a missing object. Use the strict equality operator ( === ) to check if a value is null . The typeof null returns 'object' , which is historical bug in JavaScript that may never be fixed.
Switch Case In C 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. After this, there is a colon.
In this example, it doesn't matter if result is null
or ""
, control will reach console.log("Something went wrong");
switch (result) {
case null:
case "":
console.log("Something went wrong");
break;
case "getID":
console.log("Success");
break;
default:
console.log("doSomething");
}
A switch
will catch all the falsy values separately. These values include undefined
, null
, false
, 0
, and ''
.
An if
statement will report all as false.
A snippet is worth 1000 words...
const input = [null, undefined, '', false, 0]
console.log('switch results')
input.forEach(result => {
switch (result) {
case false:
console.log("false");
break;
case "":
console.log("empty string");
break;
case null:
console.log("null");
break;
case undefined:
console.log("undefined");
break;
case 0:
console.log("0");
break;
default:
console.log("default");
}
})
console.log('if results')
input.forEach(result => {
if (!result) {
console.log(result + ' is false')
} else {
console.log(result + ' is true')
}
})
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