Suggest a feature
×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Javascript
Posted by: Chris Beardsley
Added: Jun 7, 2018 7:40 AM
Views: 12
Tags: no tags
for longer if else statements
  1. var groceryItem = 'papaya';
  2.  
  3. switch (groceryItem) {
  4.   case 'tomato':
  5.     console.log('Tomatoes are $0.49');
  6.     break;
  7.   case 'lime':
  8.     console.log('Limes are $1.49');
  9.     break;
  10.   case 'papaya':
  11.     console.log('Papayas are $1.29');
  12.     break;
  13.   default:
  14.     console.log('Invalid item');
  15.     break;
  16. }

1 comment

Chris Beardsley 17 days ago
}
The switch keyword initiates the statement, and is followed by ( ... ), which contains the condition that each case will compare to. In the example, the condition is groceryItem.
Inside the block, { ... }, there are cases. case is like the else if part of an if/else if/else statement. The word following the first case is 'tomato'. If groceryItem equalled 'tomato', that case's console.log would run.
groceryItem equals 'papaya', so the first and second case statements are skipped. The third case runs since the case is 'papaya' matches groceryItem's value. This particular program will log out: 'Papayas are $1.29'.
Then the program stops with the break keyword. This keyword will prevent the switch statement from executing any more of its code.
At the end of each switch statement, there is a default condition. If none of the cases are true, then this code will run.

Write a comment