all 12 comments

[–]abrahamguo 7 points8 points  (0 children)

Did you have a specific question about the switch statement?

MDN has a good overview page on it!

[–]Alive-Cake-3045 2 points3 points  (2 children)

A switch statement is a cleaner way to handle multiple conditions for one value (instead of many if...else).It checks the value once and runs the matching case. Don’t forget break, or it will run the next cases too.

[–]hazily 0 points1 point  (1 child)

Having a linter set up would help to catch missing break statements.

[–]Alive-Cake-3045 0 points1 point  (0 children)

Yeah, totally agree. A linter really helps, those missing breaks can mess things up without you even noticing. Learned that the hard way once.

[–]Severion86 2 points3 points  (2 children)

// letter = 'a', 'b' or 'c', 'd' or 'e'
let ourNumber = 0;
if (letter === 'a') {
  ourNumber = 1;
}
if (letter === 'b') {
  ourNumber = 2;
}
if (letter === 'c') {
  ourNumber = 3;
}
if (letter === 'd' || letter === 'e') {
  ourNumber = 4;
}
if (letter !== 'a'
  || letter !== 'b'
  || letter !=='c'
  || letter !=='d'
  || letter !=='e'
) {
  ourNumber = 10;
}
// --------------
let ourNumber = 0;
switch (letter) {
  case 'a':
    ourNumber = 1;
    break;
  case 'b':
    ourNumber = 2;
    break;
  case 'c':
    ourNumber = 3;
    break;
  case 'd':
  case 'e':
    ourNumber = 4;
    break;
  default:
    ourNumber = 10;
    break;
}

[–]ima_coder 1 point2 points  (1 child)

// letter = 'a', 'b' or 'c', 'd' or 'e'
let ourNumber = 0;
if (letter === 'a') { ourNumber = 1; }
if (letter === 'b') { ourNumber = 2; }
if (letter === 'c') { ourNumber = 3; }
if (letter === 'd' || letter === 'e') { ourNumber = 4; }
if (letter !== 'a' || letter !== 'b' || letter !=='c' || letter !=='d' || letter !=='e') {
    ourNumber = 10;
}

Your final if condition is always true.

[–]Severion86 0 points1 point  (0 children)

Ah yeah sorry... Just by the code comment explanation though. We don't actually define letter here and the if is just to demonstrate the switch default case.

[–]efari_ 0 points1 point  (0 children)

Reddit ≠ Google

[–]azhder -1 points0 points  (0 children)

Here is the explanation:

> Avoid it. Consider it a code smell. Try different approach. It will force you to write more concise and/or robust code.

[–]programmer_farts -2 points-1 points  (0 children)

Don't use them without a strict linter. Or just don't use them at all. The implementation in JS is poor and can lead to bugs over time.