Switch Statements(need to know more about answer set to "a", return "a" and not using break with last case)

Switch Statements(need to know more about answer set to "a", return "a" and not using break with last case)
0

#1

Tell us what’s happening:

I passed it using the 1st and 2nd case but later I read the hints, and used keyword return. again I tested the challenge it has been passed with giving no error and I think that setting answer to “a” or returning “a” give the same result but I didn’t understand what will happen if we use break in last case or not.

Your code so far


function caseInSwitch(val) {
  var answer = "";
  // Only change code below this line
  switch(val) {
    case 1:
      answer = "alpha";
      break;
    case 2:
      answer = "beta";
      break;
    case 3:
      return "gamma";
      break;
    case 4:
      return "delta";
  }
  
  
  // Only change code above this line  
  return answer;  
}

// Change this value to test
caseInSwitch(1);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/selecting-from-many-options-with-switch-statements/


#2

Your code should pass all the tests. If it does not, try refreshing the page and run the tests again. If you still can not pass the tests, try using Chrome as your browser for the challenges.


#3

Thanks for your guide
The test is passed but what will happen if i don’t use break with last case?


#4

Once you use the return statement, the function exits immediately, so it would not matter if there was a break statement after it, because it would never go past the return statement line.

In this challenge, you should have always been assigning a value to answer and using break, so that the return answer statement at the end would return the value. You used return on some of the case statements, but you got lucky the tests behind-the-scenes did not complain.


#5

Thanks for your useful explanation.
regards :slightly_smiling_face: