Basic JavaScript Day 3: Homework

Hi Bill,

The switch statement evaluates an expression, and matches its value in the following case clauses. If it finds a match, it would execute that code block, until it encounters a break (or reaches the end of the switch statement). So you would need to use like this:

const  quality = 10; 
// suppose we would judge 1-3 as poor, 4-5 as low, 6-7 medium, 8-10 good
// we can now evaluate 'quality' and give our opinion
// because multiple ratings can be grouped, we can make use of the 'fall through' principle
// this runs the code in the block from the case that is true, until it hits a break
switch (quality) {
  case 1:
  case 2:
  case 3:
    console.log('POOR');
    // you can run more code here .. and it will execute where quality is 1,2,3 and until it hits 'break'
    break;  // here it breaks out of the switch if quality is 1,2,3
  case 4:
  case 5:
    console.log('LOW');
    break;
  case 6:
  case 7:
    console.log('MEDIUM');
    break;
  case 8:
  case 9:
  case 10:
    console.log('GOOD'); 
    break;
  default:
    console.log('Quality UNKNOWN');
}

Now if you go back to your card counting problem, you can see that part of the puzzle is to return a value of -1, 0, 1 for certain types. That screams for a switch statement.

The switch takes an expression, so it could also be something like (a<b) and then cases true and false (although I would suggest to do this with an if :slight_smile: )

ALSO: from your code example it looks like you try to ‘call’ your switch statement? that is not possible. The switch will be executed where it is encountered. So it can be part of a function that can be called.

function myFunction(quality){

    // ...

    switch(quality){
        // ...
    }

    // ...

}

// call the function
myFunction(5);

and when you add code to your posts, if you wrap it between 3 backticks, it formats like code ``` … ```

I hope this helps?

Cheers,
Syl

3 Likes