JavaScript flow control (branching)

JavaScript flow control (branching)

1. Process Control

There are three main structures for process control:

  • Sequential structures
  • Branch structure
  • Loop Structure

These three structures represent three orders of code execution.

2. Sequential Process Control

The sequential structure is the simplest and most basic flow control in a program. It has no specific grammatical structure. The program will be executed in the order of the code. Most of the code in the program is executed in this way.

3. Branch flow control if statement

1. Branch structure

In the process of executing the code from top to bottom, different path codes are executed according to different conditions (the process of selecting multiple execution codes), thus obtaining different results.

2. if statement

// Execute code if the condition is met, otherwise do nothing if (conditional expression) {
    // Code statements executed when the condition is met}

The execution process is:

For example: an input box pops up, asking the user to enter his age. If the age is greater than or equal to 18, he is allowed to enter the Internet cafe.

var age = prompt('Please enter your age:');
        if(age > 18) {
            alert('Your age is legal, please enter!');
        }

When the input value is greater than or equal to 18, the following pop-up window appears:

3. if else statement (double branch statement)

Grammatical structure:

// If the condition is met, execute the code in if, otherwise execute the code in else if (conditional expression) {
    // [if] the condition is met, execute the code } else {
    // [otherwise] code to execute}

Execution process:

For example, write a case to check whether it is a leap year or not. Receive the year input by the user. If it is a leap year, a pop-up window will pop up indicating the leap year. Otherwise, a pop-up window will pop up indicating a common year.
Algorithm analysis:
Algorithm: A year that is divisible by 4 but not by 100 is a leap year (e.g. 2004 is a leap year, 2005 is not a leap year) or a year that is divisible by 400 is a leap year. prompt input box pops up, asking the user to enter the year, and the value is saved in a variable. Use an if statement to determine whether it is a leap year. If it is a leap year, the output statement in the if braces is executed, otherwise the output statement in the else is executed. Pay attention to the writing of && and or ||, and also note that the method of determining whether it is divisible is to take the remainder as 0.

 var year = prompt('Please enter the year to be judged:');
        if(year%400 == 0 || year % 4 == 0 && year / 100 != 0) {
            alert('This year is a leap year!');
        }else{
            alert('This year is an average year!');
        }

When entering 2004:

When entering 2005, the following popup appears:

4. if else if statement (multi-branch statement)

Grammatical structure:

// Suitable for checking multiple conditions.
if (conditional expression 1) {
    Statement 1;
} else if (conditional expression 2) {
    Statement 2;
} else if (conditional expression 3) {
   Statement 3;
 ....
} else {
    // If the above conditions are not met, execute the code here}

Execution process:

For example : Output a case for judging grades, receive the score entered by the user, and output the corresponding grade letters A, B, C, D, E based on the score. in:

  1. 90 points or above, output: A
  2. 80 points (inclusive) ~ 90 points (exclusive), output: B
  3. 70 points (inclusive) ~ 80 points (exclusive), output: C
  4. 60 points (inclusive) ~ 70 points (exclusive), output: D
  5. 60 points or less, output: E

Case Study:

According to the idea of ​​judging from large to small, a prompt input box pops up and asks the user to enter the score. This value is taken and saved in a variable. Use multi-branch if else if statements to judge and output different values ​​separately.

 var score = prompt('Please enter your score:');
        if (score >= 90) {
        alert('A');
        } else if (score >= 80) {
        alert('B');
        } else if (score >= 70) {
        alert('C');
        } else if (score >= 60) {
        alert('D');
        } else {
        alert('E');
        }

When you enter the corresponding score, the corresponding level will pop up.

4. Ternary Expression

Ternary expressions can also do some simple conditional selection. An expression consisting of a ternary operator is called a ternary expression.

expression1 ? expression2 : expression3;


Implementation ideas:

If expression 1 is true, then the value of expression 2 is returned. If expression 1 is false, then the value of expression 3 is returned. Simply put: It is similar to the shorthand of if else (double branch)
For example: enter a case of adding 0. The user enters a number. If the number is less than 10, add 0 in front of it, such as 01, 09. If the number is greater than 10, no 0 is needed, such as 20.
Case Study:
The user enters a number between 0 and 59. If the number is less than 10, add 0 to the front of the number. Otherwise, no operation is performed. A variable is used to receive the return value and output

var num = prompt('Please enter a number between 0 and 59');
        var result = num < 10 ? '0' + num : num;
        alert(result);

When the input is 2, the operation of adding 0 is performed:

When 10 is entered, the result is printed directly:

5. Branch flow control switch statement

1. Grammatical structure

The switch statement is also a multi-branch statement, which is used to execute different codes based on different conditions. switch is used when you want to set a series of options for a variable to specific values.

Grammatical structure:

switch(expression){ 
    case value1:
        // Code to be executed when expression is equal to value1 break;
    case value2:
        // Code to be executed when expression is equal to value2 break;
    default:
        // Code to be executed when the expression is not equal to any value}

switch : switch conversion, case : small example options

  • The keyword switch can be followed by an expression or a value in parentheses, usually a variable.
  • The keyword case is followed by an optional expression or value, followed by a colon and not a condition.
  • The value of switch expression is compared with the value of the case in the structure. If there is a match (===), the code block associated with the case is executed and stops when break is encountered. The execution of the entire switch statement code ends.
  • If the values ​​of all case do not match the value of the expression, the code in default is executed

Note: When executing the statements in a case, if there is no break, the execution continues with the statements in the next case.

For example, if you enter a case of querying grades, the requirements are the same as the if-else-if statement above.

var s = prompt('Please enter your score:');
var n = parseInt(s/10);
var k = null;
switch(n){
    case 10: {
        k = 'A';
        break;
    }
    case 9:
        k = 'B';
        break;
    }
    case 8:
        k = 'C';
        break;
    }
    case 7:
        k = 'D';
        break;
    }
    default: k = 'E';
}
console.log('Your grade is: '+k);

When the input is 100 points, the output is:

When the input is 73 points, the output is:

2. The difference between switch statement and if else if statement

  • Generally speaking, these two statements can replace each other. switch…case statement usually handles the case where the case is a relatively certain value, while if…else… statement is more flexible and is often used for range judgment (greater than or equal to a certain range).
  • The switch statement directly executes the conditional statement of the program after making conditional judgment, which is more efficient. The if…else statement has several conditions, so it has to be judged that many times.
  • When there are fewer branches, the execution efficiency of if… else statement is higher than that of switch statement.
  • When there are many branches, the switch statement is more efficient and has a clearer structure.

This is the end of this article about JavaScript flow control (branching). For more relevant JavaScript flow control content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JavaScript flow control (loop)
  • JavaScript flow control statement collection
  • A simple example of generating a multiplication table using JSP
  • js realizes the gorgeous effect of the multiplication table
  • Writing the multiplication table in JavaScript (two optional)
  • This article teaches you how to use JavaScript to use process control to print the multiplication table

<<:  Share 5 helpful CSS selectors to enrich your CSS experience

>>:  Detailed process of zabbix monitoring process and port through agent

Recommend

jQuery implements form validation

Use jQuery to implement form validation, for your...

List rendering instructions for efficient development of Vue front-end

v-for directive Speaking of lists, we have to men...

View the number of files in each subfolder of a specified folder in Linux

count script #!/bin/sh numOfArgs=$# if [ $numOfAr...

Database backup in docker environment (postgresql, mysql) example code

Table of contents posgresql backup/restore mysql ...

VUE realizes registration and login effects

This article example shares the specific code of ...

Detailed tutorial on building nextcloud private cloud storage network disk

Nextcloud is an open source and free private clou...

JavaScript to achieve stair rolling special effects (jQuery implementation)

I believe everyone has used JD. There is a very c...

Script to quickly list all host names (computer names) in the LAN under Linux

Recently, I have a need to list all host names in...

Solution to mysql server 5.5 connection failure

The solution to the problem that mysql cannot be ...

Install Apple Mac OS X in VMWare12 Graphic Tutorial

1. Introduction: Because my friend wanted to lear...

Native JS to implement sharing sidebar

This article shares a sharing sidebar implemented...

vue-cli introduction and installation

Table of contents 1. Introduction 2. Introduction...

Detailed explanation of creating stored procedures and functions in mysql

Table of contents 1. Stored Procedure 1.1. Basic ...