Switch Statement Question

I’ve just finished the Switch Statements challenge and have a question about how they work.

In the following function (from the challenge), at what point is the returned string assigned to the answer variable? In other words, How does returning answer give the correct output?

function switchOfStuff(val) {
    var answer = "";

    switch (val) {
        case "a":
             return "apple";
        case "b":
            return "bird";
        case "c":
            return "cat";
            return "stuff";
  return answer;  

Based on the way you wrote your code, you never assign another value to answer. Instead, you just return a value (which is fine). The last return statement will never execute anyway, because one of the switch case statements or the default statement has a return in it. In fact, you could delete the original line var answer =""; and your code would pass all the tests just the same.

Ahh! That makes sense.

So as it’s written, the answer variable is superfluous. If I wanted to keep the answer variable, I would assign the string to answer (i.e. answer = "apple") rather than to return the string. Got it.

Thank you for the prompt response!

Yes, you are correct. You would assign the relevant values to string and then after the switch statement you would just use the return answer that was already present when the challenge was first loaded.

1 Like