Switch Statements

What is the purpose of switch statements?

Switch statements are used to perform different actions based on different conditions. They are an alternative to using multiple if...else if...else statements when you need to compare the same variable or expression against multiple possible values.

Example of a Switch Statement


function selectItem(item) {
    let price = 0
  
    switch(item) {
        case 'coffee':
            price = 2
            break
        case 'sandwiches':
            price = 5
            break
        case 'salad':
            price = 4
            break
        case 'lemon cake':
            price = 3
            break
        default:
            return 'Item not found'
    }
    return `You selected ${item}. That will be $${price}`
}

console.log(selectItem('salad'))

References:

Open the console to see the output