WHY this variable in a function with switch statements and a default case?

Hi everybody, I’ve just started the JavaScript curriculum here on FCC and I have a doubt about the reason why the variable “answer” has been declared here:

function switchOfStuff(val) {
  var answer = "";
  // Only change code below this line
switch(val) {
  case "a":
  return "apple";
  break;
  case "b":
  return "bird";
  break;
  case "c":
  return "cat";
  break;
  default:
  return "stuff";
  break;
}
 // Only change code above this line
return answer;
}

switchOfStuff(1);

The exercise asks me to create a switch statement with the default case in the end. This part is ok, in fact I ran and passed the test.
What I don’t get is why var answer has been declared! It seems to me that there is no case in which answer will be returned if we have the default case that returns the strings"stuff". I tried to delete both lines of code regarding “answer” and, running the test, I pass it anyway without them.
Is there anybody who can explain the purpose of creating that variable and declaring it as an empty string? Thank you for your help!

1 Like

hey bruh, I believe that variable called answer is there just for the sole reason to use it in each case to store the “answer” and then at the end of the switch will return the actual stored answer to console. It is a better practice to do that than use return in each case. imo…

  var answer = "";
  // Only change code below this line
switch(val) {
  case "a":
  answer = "apple";
  break;
  case "b":
  answer = "bird";
  break;
  case "c":
 answer = "cat";
  break;
  default:
  answer = "stuff";
  break;
}
 // Only change code above this line
return answer;
}

switchOfStuff(1);
1 Like

OOOH, right!!! :sweat_smile:
It makes a lot of sense now, thank you so much for your help. :grinning:

1 Like