Introduction to JavaScript : Conditionals using switch case

Conditionals using switch case

Another means by which we can execute certain statements based on a condition is using the 'switch...case' syntax. This condittional style makes code more readable and provides a means to compare multiple values via a single switch statement.

Syntax:

switch (<variable or constant>) {
   case <value1>:
      <statements>
      break
   case <value2>:
      <statements>
      break
   default:
      <statements>
}

The statements in the 'case' whose value is equal to the constant in the switch will be executed. If not case value is equal to the constant in the switch, the dafault block will then be executed.

Example:

const x = 5
switch (x) {
   case 2:
      console.log("Case 2 block is executed")
      break
   case 4:
      console.log("Case 4 block is executed")
      break
   case 5:
      console.log("Case 5 block is executed")
      break
   default:
      console.log("Default block is executed")
}

Output will be:

Case 5 block is executed

since the third case value (5) is equal to the value of x.

In case none of the case values was equal to 5, the default block would execute.


course logo
Introduction to JavaScript
Number of sections:
10
Content length:
Delivery formats: