+ 5

Clarification on Example

The example they give for a javascript switch example: What is 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); } The answer is 8. But my question is, why? Is it because there was no third case, or because there was no matching third case for the variable?

20th Aug 2017, 10:27 PM
Samantha Jordan
Samantha Jordan - avatar
7 Antworten
+ 13
Because the was no case matching the value of x (so case "3") and the default is always taking into account (unless, for example, a break statement was used before it) so now "x + 5" is writing which is 8.
20th Aug 2017, 10:41 PM
LynTon
LynTon - avatar
+ 2
If no [case] is match the [default] section will be run ... every language is same.
2nd Sep 2017, 5:00 AM
Akbar Khalilzadeh
Akbar Khalilzadeh - avatar
+ 2
Ребята! Всё просто. х=3 это не значение. 3 - это имя case. Наша программа пытается найти "case 3". Она находит "case 1" и "case 2", пропускает их, так как они не являются решением задачи, то есть, не являются "case 3". Ищет дальше, пытается найти "case 3" и не найдя его выполняет условие "default", то есть, "x+5"!
7th Feb 2018, 8:54 PM
Швандырев Василий
Швандырев Василий - avatar
+ 1
8
10th Aug 2021, 9:26 PM
W.G.A.C.Nandasena
W.G.A.C.Nandasena - avatar
0
document.write
9th Dec 2020, 4:37 PM
Turikumana Isaie
Turikumana Isaie - avatar
0
the answer is 8
18th Jul 2021, 12:01 AM
Abdulazeez Ridwan
Abdulazeez Ridwan - avatar
- 2
fifty
28th Aug 2019, 12:57 AM
Jimson Ygot
Jimson Ygot - avatar