Course

'switch' Statement

Loading...

In this lesson, you'll learn about the switch statement in JavaScript, which is useful for performing different operations based on various conditions.

Switch Statement

The switch statement is extremely similar to the statement. They can be used interchangeably, but there are situations where a switch is preferred.

With statements, you mostly have just a few conditions: one for the , a few for the , and the final statement. If you have a larger number of conditions, you might want to consider using the statement. Let's explore how it works.

The statement is used to perform different operations based on different conditions.

Let's say that you have a variable called .

var superHero = 'Captain America';

Based on the name of the superhero, you want to display his voice line.

We can do that using the . The takes in a value and then checks it against a bunch of :

switch (superHero) {
    case 'Iron Man':
        console.log('I am Iron Man...');
        break;
    case 'Thor':
        console.log('That is my hammer!');
        break;
    case 'Captain America':
        console.log('Never give up.');
        break;
    case 'Black Widow':
        console.log('One shot, one kill.');
        break;
}

How It Works

In this example, we passed the variable to the statement.

It executes the first check with a triple equal sign. It looks something like this:

'Captain America' === 'Iron Man'

Since this evaluates to , it skips it and goes to the next one. As soon as it finds the one that matches correctly, it prints the output.

The Break Keyword

What is that keyword?

The keyword ends the when we get the correct .

If we omit the statement, the next will be executed even if the condition does not match the .

The Default Case

And finally, what if none of the names in the match the name of our ? There must be something like an statement, right? There is! That something is called .

If none of the match, the case is going to be executed. We can implement it like this:

switch (superHero) {
    case 'Iron Man':
        console.log('I am Iron Man...');
        break;
    case 'Thor':
        console.log('That is my hammer!');
        break;
    case 'Captain America':
        console.log('Never give up.');
        break;
    case 'Black Widow':
        console.log('One shot, one kill.');
        break;
    default:
        console.log('Enter a valid superhero name');
        break;
}

That's it! Now you know how to use the . As always, I would advise going into the Chrome console or a code sandbox and playing with it yourself. You learn the most by trying things yourself.

Loading...

0 Comments

"Please login to view comments"

glass-bbok

Join the Conversation!

Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.

Upgrade your account
tick-guideNext Lesson

Ternary Operator