LennyShort.com

The JavaScript "Switch" Statement

The "switch" statement in JavaScript can be used in place of an if or if-else statement to make the code more concise. A series of several if-else statements can get cumbersome, so the "switch" statement makes the code easier to read and understand. Here's an example function that uses 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 `Sorry, we don't sell ${item}`
    }
    return `You selected ${item}. That will be $${price}`
}

Calling this function in a console.log statement:

console.log(selectItem('coffee'))
// Output: "You selected coffee. That will be $2."

This output would vary depending on the value that is passed into the selectItem function. The "default" keyword near the end of the "switch" statement would match any string that does not already have a match in the function, such as "biscuits".

What I'm reading:

What I've read recently:

What's on my reading list: