Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for a switch case with null value in javascript

Tags:

javascript

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

like image 311
user3363453 Avatar asked Mar 18 '14 05:03

user3363453


People also ask

How do you handle a null case in a switch case?

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 { // ... }

How check data is null or not in JavaScript?

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.

Can we check condition in switch case?

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.


2 Answers

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");
}
like image 87
thefourtheye Avatar answered Sep 28 '22 06:09

thefourtheye


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')
  }
})
like image 30
Steven Spungin Avatar answered Sep 28 '22 07:09

Steven Spungin