JavaScript basic conditional statement 2.0


5. Conditional statement

a. If statement

Grammar:If (conditional expression) / / conditional expression: either true or false


The code to be executed if the condition is satisfied;


If else statement

If (conditional expression)


Meet the conditions and execute the code;

}else {

Code executed if the condition is not met;


be careful: else cannot be used alone


practice:Grade n [90 ~ 100] a

         [80~90)     B

                           [70~80)     B

         [60~70)     B

[0 ~ 60) fail

code:Method 1

var n = 95;
  if(n>=90 && n<=100) {


  }else if(n>=80 && n<90){


  }else if(n>=70 && n<80){

  }else if(n>=60 && n<70){


  }else {

    Alert ("fail");


Method 2

if(n<60) {

    Alert ("fail");

  }else if(n<70) {


  }else if(n<80) {


  }else if(n<90) {


  }else if(n<100) {



b. Switch statement

Syntax: switch (n){

Case X1: Code 1…; break;

Case x2: Code 2…; break;

Case X3: Code 3…; break;


Case X1: Code 1…; break;


be careful:Case is followed by a specific value and cannot be a range [enumeration]

Switch (variable), not like if statement and condition

Limitations:Switch is not flexible enough and not as widely used as if, but it is reasonable to exist.



var n = 10;

switch(n) {

  case 1: alert("hello world"); break;

  Case 2: alert; break;

  Case 3: alert; break;

  default:alert Break; break; break; break; break;


C. While statement


While (condition){

Loop body [execute when conditions are met]


Note: this can easily lead to infinite loops


The finite cycle condition is as follows

(1) , initial variable

(2) The condition is a bounded range

(3) In the loop body, operate on the initial variable


Debug — > view language execution order:

(1) . breakpoints need to be set

(2) Debugging tool with browser [F12]

(3) And [F10] step by step

(4) And [F8] runs to the next breakpoint. If there is no breakpoint, it ends directly


Var I = 10; // initial variable

While (I > 0) {// the condition is a bounded range

  Debugger; // set breakpoint

  console.log (the "condition holds" + I);

  I --; // operate on the initial variable


d. Do while statement

Grammar: do{


Variable operation

}While (condition);


var i = 50; 
do {
    Alert ("the score is" + I + "unqualified");