If you want to return a value other than undefined from a function then you always need to return (for single line arrow functions the return is implied). All of the solutions for these two challenges use return to return a value.
I think you are referring to the fact that one of the solutions uses return in the switch block for every case while the other sets answer to the return value in the switch and then returns answer after the switch. They are both correct, you can do either.
Although I will note that the solution that returns for each case doesn’t need the break after each return and doesn’t need the return at the very end and doesn’t need the answer variable at the beginning.
Personally, for simple functions like these I would just return after each case.
Thanks for explaining both work, but for this situation one solution (linked) has one and the other uses the other. Why is that? I’m assuming there is a level of significance since one is not accepted as the right answer, but if not please let me know
Personal preference. Both solutions work just fine. You can either immediately return a value after each case or you can wait and return after the switch.
case "a":
answer = "apple";
break;
Just to be clear, this doesn’t return a value itself. It saves the value you want to return to answer and then you return answer at the end of the function.
Understood. For the sake of the examples and the course material it didn’t appear there would be a good reason to pick one vs the other. The material seems to have made the switch on it’s own I guess. If anyone sees a reason otherwise please let me know. Thanks!
if you can show the code for that, you can get an answer on why
If you have a question about a specific challenge as it relates to your written code for that challenge, just click the Ask for Help button located on the challenge. It will create a new topic with all code you have written and include a link to the challenge also. You will still be able to ask any questions in the post before submitting it to the forum.
Hi @ILM since this question had two challenges I was comparing I used a link to the guides containing the codes as solutions. My code ended up being the same as those solutions.
As far as I can tell both challenges works with both methods.
I will say if you use a return, the break becomes unreachable code and likely shouldn’t be there. Not really sure why the solution 1 code that uses return has the break as well.
Edit: I see that the break is actually part of the requirements. So the solution with the return is a bit of an odd one to show. Not to mention it leaves the variable and the return of the variable as well, which doesn’t really make sense.