Switch Statement Question

Switch Statement Question
0

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";
             break;
        case "b":
            return "bird";
            break;
        case "c":
            return "cat";
            break;
        default:
            return "stuff";
            break;
    }
  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.