+ 3
Need Help Understanding Switch Statement Example
Can someone please explain this to me in pseudo code? let numberTen = 10; let numberFive = 5; let equalTo; switch(equalTo){ case 10 === 5: equalTo = true; break; default: equalTo = false; } Is 10 === 5 the parameters for the case? Could it be, since it's obviously not true, it breaks then moves to default which is set to false? How is the expression in the switch working? Is it reading the set value for the variable then checking the condition to see of it matches? I don't understand why the expression of the switch is equalTo. I understand that switch statements act like an if...else statement. If it could be plainly explained in step by step pseudo code, I would appreciate it.
4 Answers
+ 3
The switch statement starts by taking one parameter, which in this case is the variable equalto. Then, it goes through every case until it finds one that evaluates to true. Once it does, it goes through the statements within the block and if it has a break statement, then the switch statement gets terminated. If break weren't there, it would go through the statements for all of the other cases.
If the switch statement runs through without finding a case that evaluates to true, then it heads to the default case (If there is one) and runs the statements within that block. A break statement wouldn't be needed within a default case because it will always be the last case to run.
The same statement above could be written like this:
let numberTen = 10;
let numberFive = 5;
let equalTo;
if(10 === 5){
equalTo = true;
}
else{
equalTo = false;
}
Hope this helped!
+ 3
Well, not exactly. The parameter, in this case, is only used as reference to change its value. In some cases, the parameter may not even have a use!
What the case is checking for is to see if the condition next to it is true, and if it is, it runs the statements. Because 10 is not equal to 5 in the example, it doesn't run the statements within and goes to the next case, which doesn't exist. Because there is no other cases and the only one evaluated to false (10 does not equal 5), it ran the default case which set equalTo to false.
Hope this cleared that up!
+ 2
So, first the switch takes the parameter (equalTo) and goes through each case to see if it's true. Since the first case has equalTo set to true, it checks the condition of the case which is 10===5. But it's not true, so it breaks then continues on. Since there is only the default left, equalTo is false.
Okay, that makes sense. Thank you so much!
+ 2
Oooh, okay. I was close. Thank you for the help! I appreciate it!