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 matches in the case clause, and if default clause is given that statement block will be executed, else switch statement closes.

Syntax

[] - This symbol denotes optional.

Flowchart

switch statement flowchart

Example

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");)