Switch Case command in JavaScript

You can use multiple if ... else ... if statements as in the previous chapter to make a multiple choice branch. However, it is always not the best solution, especially when all branches depend on the value of a single variable.

You can use multiple if . else . if statements as in the previous post to make a branch of multiple choices. However, it is not always the best solution, especially when all branches depend on the value of a single variable.

Starting with JavaScript 1.2, you can use a switch command to correctly handle this situation, and it's actually more efficient than repeating if . else if statements .

Implementation diagram

The following diagram explains the switch-case command to work:

Picture 1 of Switch Case command in JavaScript

Syntax

The goal of a switch command is to provide an expression to estimate and several different commands to execute on the value of the expression. The interpreter checks each case - the case with the value of the expression until a match is found. If there is no match, a default condition - will be used by default .

 switch ( expression ) { case condition 1 : statement ( s ) break ; case condition 2 : statement ( s ) break ; . case condition n : statement ( s ) break ; default : statement ( s ) } 

Break command instructs the end of each specific case. If they are omitted, the interpreter will continue to execute each instruction in each of the following cases.

We will discuss the break command in the Loop control chapter.

For example

Try the following example to execute the switch-case command

  type = "text/javascript" >  
 Set the variable to different value and then try. 

Result:

 Entering block switch 
Good job
Block Exiting switch
Đặt biến vào giá trị khác nhau và thử thử .

Break commands play an important role in switch-case commands. Try the following code using the switch-case command without any break commands.

  type = "text/javascript" >  
 Set the variable to different value and then try. 

Result:

 Entering block switch 
Good job
Pretty good
Passed
Not so good
Failed
Unknown grade
Block Exiting switch
Đặt biến vào giá trị khác nhau và thử thử .

According to Tutorialspoint

Previous lesson: if . else command in JavaScript

Next: The while loop in JavaScript

Update 25 May 2019
Category

System

Mac OS X

Hardware

Game

Tech info

Technology

Science

Life

Application

Electric

Program

Mobile