Question about switch

0 axel vincent · January 28, 2016
Hi! Anyone can tell me why my switch doesn't work?

function myTest() {
var answer = "";
 
  switch (answer) {
   case "a":
      answer = "apple";
        break;
   case "b":
      answer = "bird";
        break;
   case "c":
      answer = "cat";
          break;
   default:
      answer = "stuff";
  }
  return answer;  
  }
myTest("a");

Post a Reply

Replies

Oldest  Newest  Rating
+1 Nikita Volobuev · January 29, 2016
Your switch is okay. I think the problem is that you don`t pass the variable to it.
Correct code:


function myTest(myVar) {
var answer="";
switch (myVar) {
case "a":
answer = "apple";
break;
case "b":
answer = "bird";
break;
case "c":
answer = "cat";
break;
default:
answer = "stuff";
}
return answer;
}
myTest("a");
0 Nicholas Eason · January 30, 2016
There's nothing wrong with that Switch. However, unlike what Nikita said, are you sure that the function is called?
+1 Linguist Llama · January 30, 2016
Think about switch (answer) when answer is ""...
0 Nicholas Eason · January 30, 2016
Linguist, he has a default case. If the String doesn't  match any of the cases it should trigger default.
  • 1

Javascript

107,301 followers
About

A scripting language that is added to standard HTML to create interactive effects, apps, games for the browser.

Links
Moderators