How works exactly "switch statement" in JS — I maked crasy chatgpt | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
0

How works exactly "switch statement" in JS — I maked crasy chatgpt

I had to do an exercice about switch : What’s the output of this code? var x = 3; switch (x) { case 1: document.write(x); break; case 2: document.write(x+2); break; default: document.write(x+5); } I was hesitated between two answer 8 or 3, the result is 8, well!! but i wasn't sure to understand why, so I asked for it to chatgpt … and voila: as I assumed he tells me " the initiale value of x is var x = 3; so (x+5) is : 3 + 5 = 8 ok, so I asked for it in the "CASE 2" we have "document.write(x+2); "so the result is 3 + 2 = 5 ? he said yes ! SO I didn't understand why the answer is 8 rather 3 ? because in the "CASE 1: document.write(x);" and since x = 3, why the answer is not 3 ?

2nd Oct 2023, 10:34 AM
Boudahh Da
Boudahh Da - avatar
4 Réponses
+ 5
The switch statement looks for a match between its expression (x) and the values in the case statements. In your code, the case values are 1, 2, and default. Since x is 3, there's no exact match with any case, so it goes to the default case. In the default case, it calculates 3 + 5, which equals 8. Therefore, the output is 8. So if you do var x = 2 what would the output be?
4th Oct 2023, 3:31 AM
Chris Coder
Chris Coder - avatar
+ 4
The "case" operator it searches for a comparison with the value of x and if it finds nothing, the "default" operator is triggered. That is, it is analogous: if (1==x) document.write(x); else if (2==x) document.write(x+2); else document.write(x+5);
2nd Oct 2023, 11:12 AM
Solo
Solo - avatar
+ 3
Boudahh Da , In JavaScript switch cases, the `default` keyword is used when the current object does not match any switch case. Or in other words, the code below it will execute if non of the switch case executes. The `default` keyword should be placed after you placed all the cases for the switch statement, and it should be used once in every switch statement. In the code you provided, it executes the line `document.write(x+5)` in the switch case, since none of the case matches(or executes). If you don't understand how switch case works, I'll tell you: - switch cases are rarely used in programming, but it's used for checking a bunch of values if one of them matches the given object. - switch cases are usually served for `enum` objects.
2nd Oct 2023, 11:11 AM
Dragon RB
Dragon RB - avatar
0
Chris Coder, So if you do var x = 2 what would the output be? I guess 5 (3 + 2) oops sorry 4 (2 + 2)
6th Oct 2023, 8:52 AM
Boudahh Da
Boudahh Da - avatar