Switch Statement

Switch Statement

  • Used an alternative to if..else if statements

  • Evaluates an expression, and matches that expression against each of the case clauses

  • if there’s a match, the statements associated with that case clause will be executed

  • The break keyword must be used to exit the Switch statement after a match is found

switch(expression) {
  case x:
    // execute code block when expression === x
    break // <- break must be called to exit the switch statement after the match
  case y:
    // execute code block when expression === y
    break // <- break must be called to exit the switch statement after the match
  default:
    // execute code block when expression === when none of the above cases match
}

Example

const food = "apple"

switch(food) {
  case 'pear':
    console.log("I like pears")
    break
  case 'apple':
  case 'oranges':
    console.log("I like apples & oranges")
    break
  case 'grapes':
    console.log("I like grapes")
    break
  default:
    console.log("Your fruit selection is weak :(")
}

JS Bin on jsbin.com

Exercise

Rewrite the following if..else if statement using a switch statement:

const yourGrade = "C"

if (yourGrade === "A") {

  console.log("You earned an A!")

} else if (yourGrade === "B") {

  console.log("You earned a B")

} else if (yourGrade === "C") {

  console.log("You earned a C")

} else {
  console.log("You earned less than a C")
}

JS Bin on jsbin.com