Clarification on Example | Sololearn: Learn to code for FREE!

+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?

8/20/2017 10:27:36 PM

Samantha Jordan

7 Answers

New Answer

+12

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.

+2

If no [case] is match the [default] section will be run ... every language is same.

+2

Ребята! Всё просто. х=3 это не значение. 3 - это имя case. Наша программа пытается найти "case 3". Она находит "case 1" и "case 2", пропускает их, так как они не являются решением задачи, то есть, не являются "case 3". Ищет дальше, пытается найти "case 3" и не найдя его выполняет условие "default", то есть, "x+5"!

+1

0

document.write

0

the answer is 8

-2