switch statement in javascript

switch statement in javascript

switch statement compare the given expression with other values specified in the case clause and if any one of them matches, that particular case clause block will be executed.

If no expression are matched in the case clause, and if default clause is given that statement block will be executed, else switch statement closes.


[] - This symbol denotes optional.


switch statement flowchart


Try Yourself

If break is not given all the case blocks will be executed.

Execution flow of above example - image explanation

  • Variable a is created and value 1 is assigned (var a=1).
  • Value of a is compared with the first case value(1) and it returns true (1==1).
  • First case block is executed (alert("One");).
  • break statement break the switch statement.
  • switch statement ends and the control execute the next statement (alert("Finished");)