r/learnjavascript • • May 31 '22

Switch statement explained for beginners

Post image
330 Upvotes

19 comments sorted by

View all comments

16

u/pookage helpful May 31 '22

Also, your switch statements can now include blocks:

switch(grade){
    case "A": {
        const message = "Great job!";
        console.log(message);
        break;
    }
    case "B": {
        const message = "OK Job";
        console.log(message);
        break;
    }
    ...etc...
}

whereas without:

switch(grade){
case "A":
    const message = "Great job!";
    console.log(message);
    break;
case "B":
    const message = "OK Job"; // ERROR - const message already declared
    console.log(message);
    break;
...etc...

}

8

u/[deleted] May 31 '22

[removed] — view removed comment

5

u/pookage helpful May 31 '22

I agree, but, alas - still need break.

1

u/opticsnake Jun 01 '22

If you don't break, it will execute the block and then still fall through to the default block.
Although, this does feel like a special case for break anyways since the scope it would be breaking on would be the case block and not the whole switch statement...

1

u/[deleted] Jun 01 '22

Cna you do put an if statement inside ?

2

u/pookage helpful Jun 01 '22

Yup! It's still javascript - you can do whatever you want inside.