Switch Statements 😂

Tell us what’s happening:
Describe your issue in detail here. The below code works but produces odd results, when i run the code i get -
alpha
alpha
beta
gamma
delta
alpha

  **Your code so far**

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

caseInSwitch(1);

On the other hand if i switch the “console.log” command to a “return” command it does something to the formatting of the “break” statement but works perfectly. Why does “console.log” not work perfectly here.

  **Your browser information:**

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

Challenge: Selecting from Many Options with Switch Statements

Link to the challenge:

console.log doesn’t pass the result out of the function.

1 Like

There are few topics you should read more about- how return works and functions in general and maybe, how does it correspond with the switch break statement.

When you call caseInSwitch with argument 1, what happens is, you set the value of answer to an empty string, you enter the switch statement, you log “alpha” in the console(since we talk case 1) and then we return the value of answer from the function, which is still an empty string. Nowhere we reassigned its value. If we were to say const returnValue = caseInSwitch(1), returnValue will be value of "", because that is what the function is returning, altho it will log “alhpa” in the console.
Now, if we were to say instead of console.log("alpha") - return "alpha", whenever the switch enters that case, the function will return that value and finish its lifetime. Possible solutions are to either return directly in the cases, whatever value you wish to return in the specific case, or reassign the value of answer and then proceed to return answer in the end.

1 Like

That makes sense, but to clarify - You are saying:

That because the console.log command is still within the curly braces of the function it cannot log the result to the console.

No. I’m saying that console.log doesn’t make a return from the function.

What happens if you try

const result = caseInSwitch(3);
console.log("the returned value was" + result);
1 Like