| Viewed 42 times

how to switch Statement in javascript


how to switch Statement in javascript

1 Answer
Mikdam Qandeel
Answered
0

The switch statement evaluates an expression and executes code if it's matching a specific case.

Example:

function vowel(le) {
  switch (le) {
  case 'u':
     return "it's vowel";
  case 'a':
     return "it's vowel";
  case 'e':
     return "it's vowel";
  case 'o':
     return "it's vowel";
  case 'i':
     return "it's vowel";
  }
  default :
    return "it's NOT a vowel";
}

console.log( vowel(a) );

Output:

It's vowel

If you have different cases you can separate them using break as in the previous example.

But if you have different cases with a similar statement you can remove the break .

Example:

function vowel(le) {
  switch (le) {
  case 'u':
  case 'a':
  case 'e':
  case 'o':
  case 'i':
     return "it's vowel";
  default :
     return "it's NOT a vowel";
  } 
}

console.log( vowel(a) );

Output:

It's a vowel

And the default it's autorun if the expression doesn't match any case.