FAQ: Conditional Statements - The switch keyword

That is a given for all of us. Take it in stride, and don’t hurry. It will come. This is not a race.

1 Like

Why does the switch statement require only one set of {} curly bracket

switch(athleteFinalPosition) {
  case 'first place':
    console.log('You get the gold medal!');
  case 'second place':
   console.log('You get the silver medal!');
  case 'third place':
   console.log('You get the bronze medal!');
}

whereas for if…else, a curly bracket is required for each if, else if & else…

let groceryItem = 'papaya';

if (groceryItem === 'tomato') {
  console.log('Tomatoes are $0.49');
} else if (groceryItem === 'papaya'){
  console.log('Papayas are $1.29');
} else {
  console.log('Invalid item');
}

The switch statement evaluates an expression and matches the expression’s value to a case label. It uses a single set of curly braces to enclose all the case clauses and their associated code blocks. The case clauses are considered as labels within the switch statement block, and the switch block itself contains all the cases.

The if...else statement evaluates conditions in sequence. Each if, else if, and else block can have its own curly braces {} to define the scope of the code that should be executed when the condition is met. However, when there is only one line of statement involved the scope of the conditional blocks, the curly braces can be omitted as such:

let groceryItem = 'papaya';

if (groceryItem === 'tomato')         console.log('Tomatoes are $0.49');
else if (groceryItem === 'papaya') console.log('Papayas are $1.29');
else                                                   console.log('Invalid item');
2 Likes

Does using the switch keyword really save you that much time if you have to account for 100 different values? Want to make sure i’m not missing anything…