JavaScript switching conditions

Understand the basics of JavaScript transition conditions

Oneif/elseWhen you have several options, the statement is good.

However, if they are too many, it may be too much. Your code looks too complicated.

In this case, you might want to useswitchConditional:

switch(<expression>) {
  //cases
}

Based on the result of the expression, JavaScript will trigger a specific situation that you define:

const a = 2
switch(a) {
  case 1:
    //handle case a is 1
    break
  case 2:
    //handle case a is 2
    break
  case 3:
    //handle case a is 3
    break
}

You must add onebreakThis statement must be used in each case, otherwise JavaScript will also execute the code in the next case (sometimes this is useful, but beware of errors). When used inside a function, if the switch defines a return value, do not usebreakyou can use itreturn:

const doSomething = (a) => {
  switch(a) {
    case 1:
      //handle case a is 1
      return 'handled 1'
    case 2:
      //handle case a is 2
      return 'handled 2'
    case 3:
      //handle case a is 3
      return 'handled 3'
  }
}

You can providedefaultIn special cases, it is called when there is no case-processing expression result:

const a = 2
switch(a) {
  case 1:
    //handle case a is 1
    break
  case 2:
    //handle case a is 2
    break
  case 3:
    //handle case a is 3
    break
  default:
    //handle all other cases
    break
}

Download mine for freeJavaScript beginner's manual


More js tutorials: