+ 1

Can anyone give a good example for javascript switch or switch statements?

I am a bit confused about switch statements and how to use them in my codes, any practical example?

22nd Jul 2017, 9:32 AM
Shehzad
Shehzad - avatar
2 Answers
22nd Jul 2017, 10:01 AM
Eligijus Silkartas
Eligijus Silkartas - avatar
+ 4
let arg = prompt("Enter a value"); switch(arg) { case '0': case '1': alert('One or zero'); case '2': alert('Two'); break; case 3: alert('Never executes!'); default: alert('An unknown value') } Equality check is always strict. The values must be of the same type to match. For 0, 1, the first alert runs. For 2 the second alert runs. But for 3, the result of the prompt is a string "3", which is not strictly equal === to the number 3. So we've got a dead code in case 3! The default variant will execute.
22nd Jul 2017, 10:00 AM
Вап