Back to Course

Introduction to JavaScript

0% Complete
0/0 Steps
  1. JavaScript: Basics
    9Topics
    |
    10 Quizzes
  2. JavaScript: Variables
    9Topics
    |
    10 Quizzes
  3. JavaScript: Conditional Statements
    10Topics
    |
    11 Quizzes
  4. JavaScript: Functions
    10Topics
    |
    11 Quizzes
  5. JavaScript: Scope
    6Topics
    |
    7 Quizzes
  6. JavaScript: Arrays
    11Topics
    |
    12 Quizzes
  7. JavaScript: Loops
    8Topics
    |
    9 Quizzes
  8. JavaScript: High Order Functions
    3Topics
    |
    4 Quizzes
Lesson 3, Topic 10
In Progress

JavaScript: Switch keyword

Yasin Cakal 2 Nov 2021
Lesson Progress
0% Complete

If we need to check multiple conditions, else if statements are a great tool. We frequently need to check multiple values in programming and handle each of them differently. Consider the following example:

let Item = 'Hammer';
 
if (Item === 'Nails') {
  console.log('Nails are $0.49');
} else if (Item === 'Drill machine'){
  console.log('Drill Machine are $1.29');
} else {
  console.log('Item not found');
}

//Output: Item not found

We have a series of else if conditions in the code above that check for a value that matches an Item variable. Our code works perfectly, but imagine having to check 100 different values! Writing that many more if statements sound like a chore!

A switch statement provides a more readable and writable alternative syntax. The following is an example of a switch statement:

let Item = 'Screw Driver';

switch (Item ) {
  case 'Hammer':
    console.log('Hammer is $0.49');
    break;
  case 'Nails':
    console.log('Nails are $1.49');
    break;
  case 'Screw Driver':
    console.log('Screw Driver is $4.29');
    break;
  default:
    console.log('Item not found');
    break;
}

//Output: Screw Driver is $4.29
  1. The statement is started with the switch keyword, which is followed by (…), which contains the value that will be compared in each case. The value or expression of the switch statement in this example is Item.
  2. There are multiple cases within the block{...} The case keyword determines whether the expression matches the value specified after it. Hammer is the value after the first case. If Item equaled Hammer, console.log() would be called in that case.
  3. The value of Item is Screw Driver, so the third case runs Screw Driver is $4.29 is logged to the console.
  4. The break keyword instructs the computer to exit the code block and not to execute any additional code or check any other cases. Note that without break keywords, the first matching case will run, but every subsequent case—including the default—will run regardless of whether it matches or not. This differs from if/else conditional statements, which only execute one block of code.
  5. A default statement placed at the end of each switch statement. If none of the cases are true, the default statement’s code will be executed.

Responses

Leave a Reply

%d bloggers like this: