ifstatements

Grammar:

if (condition) {
    statement1
} else {
    statement2
}
Copy the code
  • condition: expression, the evaluation result will be converted to a Boolean value, istrueExecute the statement statement1, which isfalseExecute the statement statement2.
  • More than one can be used continuouslyifStatements.
if (i > 25) { 
    console.log("Greater than 25."); 
} else if (i < 0) { 
    console.log("Less than 0."); 
} else { 
    console.log("Between 0 and 25, inclusive."); 
}
Copy the code

The best practice is to use blocks of statements, even if there is only one line of code to execute. This is because statement blocks avoid confusion about what is executed under what conditions.

whilestatements

A while statement is a test-loop statement that checks the exit condition before executing the code inside the loop. Therefore, the code inside the while loop might not execute.

Grammar:

while(expression) {
    statement
}
Copy the code
  • condition: expression, the evaluation result will be converted to a Boolean value, istrueExecute the statement.

Example:

let i = 0; 
while (i < 10) { 
    i += 2; 
} 
Copy the code

In this example, the variable I starts at 0 and increments by 2 each time through the loop. As long as I is less than 10, the cycle continues.

Infinite loop: while (true) {… }.

do... whilestatements

do… A while statement is a post-test loop in which the code in the body of the loop is executed before the exit condition is evaluated. In other words, the code in the loop executes at least once.

Grammar:

do { 
    statement 
} while (expression); 
Copy the code

Example:

let i = 0; 
do { 
    i += 2; 
} while (i < 10); 
Copy the code

In this case, the loop repeats as long as I is less than 10. I starts at 0 and increases by 2 each time.

forstatements

The for statement is also a test-first statement, but adds initialization code before entering the loop and expressions to execute after the loop executes.

Grammar:

for (initialization; expression; postLoopExpression){
statement
}
Copy the code
  • initialization: Initialization code
  • expression: Exit condition evaluation expression
  • postLoopExpression: The expression to execute after the loop
let count = 10; 
for (let i = 0; i < count; i++) { 
    console.log(i); 
} 
Copy the code

In the initialization code of the for loop, you can actually declare keywords without using variables. However, the iterator variables defined by the initialization are almost impossible to use after the loop is completed. Therefore, the clearest way to write this is to declare an iterator variable using let, which limits the scope of the variable to the loop.

Initialization, conditional expressions, and post-loop expressions are not required. Thus, an infinite loop can be created by writing:

for (;;) { // Infinite loop
 doSomething(); 
} 
Copy the code

Notice the two for; Must exist, otherwise syntax errors will occur.

for... instatements

for… The IN statement is a strictly iterative statement that enumerates non-symbolic key attributes in an object.

Syntax: for (property in expression) statement

  • property: local variable, used to hold key names
  • expressionObject: (The object ofnullundefined, the loop body is not executed)
for (const propName in window) { 
    document.write(propName); 
} 
Copy the code

This example uses for… The IN loop displays all properties of the BOM object Window. Each time the loop executes, the propName variable is assigned a window object property until all of the window’s properties have been enumerated.

As with the for loop, const in the control statement is not required here. But to ensure that this local variable is not modified, const is recommended.

Properties of objects in ECMAScript are unordered, so for… The IN statement does not guarantee the order in which object attributes are returned. In other words, all enumerable attributes are returned once, but the order in which they are returned may vary from browser to browser.

for... ofstatements

for… The of statement is a strict iteration statement that iterates through the elements of an iterable.

Syntax: for (property of expression) statement

for (const el of [2.4.6.8]) { 
    document.write(el); 
} 
Copy the code

As with the for loop, const in the control statement is not required here.

for… The of loop iterates over the elements in the order in which the iterable’s next() method produces the values.

If the variable trying to iterate does not support iteration, then for… The of statement throws an error.

Label statement

Label statements are used to label statements.

Syntax: label: statement

start: for (let i = 0; i < count; i++) { 
    console.log(i); 
} 
Copy the code

In this case, start is a label that can be referenced later with a break or continue statement. A typical use of label statements is nested loops. The tag is the only way to break/continue to call up the nested loop to go outside.

The tag does not allow us to move anywhere in the code. Break or continue can only be called inside the loop, and the label must be somewhere above the directive.

break label; // Cannot jump to this tag

label: for(...).Copy the code

breakcontinuestatements

  • Break: to end the current loop;
  • Continue: Skip the current loop and execute the next loop;
// break
let num = 0; 
for (let i = 1; i < 10; i++) { 
    if (i % 5= =0) { 
        break; 
    } 
    num++; 
} 
console.log(num); / / 4. When I is equal to 5, the break statement causes the loop to exit and num is not incremented

// continue
let num = 0; 
for (let i = 1; i < 10; i++) { 
    if (i % 5= =0) { 
        continue; 
    } 
    num++; 
} 
console.log(num); / / 8. The value of num is 8 instead of 9 because the continue statement causes it to increment by one less time
Copy the code

Both break and continue can be used with label statements to return to a specific location in the code. This is usually in a nested loop, as shown in the following example:

let num = 0; 
outermost: 
for (let i = 0; i < 10; i++) { 
    for (let j = 0; j < 10; j++) { 
        if (i == 5 && j == 5) { 
            breakoutermost; } num++; }}console.log(num); / / 55
Copy the code

In this case, the outerMost tag identifies the first for statement. Normally, each loop is executed 10 times, meaning that the num++ statement is executed 100 times, and the console.log result should be 100 at the end of the loop. However, the break statement introduces a variable, the label to which you want to exit. Adding the tag not only causes break to exit the inner loop (using the variable j), but also the outer loop (using the variable I). The loop stops when both I and j are equal to 5, and the value of num is 55.

The continue statement can also use labels, as shown in the following example:

let num = 0; 
outermost: 
for (let i = 0; i < 10; i++) { 
    for (let j = 0; j < 10; j++) { 
        if (i == 5 && j == 5) { 
            continueoutermost; } num++; }}console.log(num); / / 95
Copy the code

This time, the continue statement forces the loop to continue, but not the inner loop, but the outer loop. When both I and j are equal to 5, continue is executed, which jumps to the outer loop and continues, causing the inner loop to execute 5 fewer times, resulting in num equal to 95.

Combining tag statements with break and continue can achieve complex logic, but it is also error-prone. Be sure to use descriptive text for tags and not too deeply nested.

With statement

The purpose of the with statement is to set the code scope to a specific object.

Syntax: with (expression) statement;

The main scenario for using the with statement is repeated operations on an object, where the code is scoped to provide convenience, as shown in the following example:

let qs = location.search.substring(1); 
let hostName = location.hostname; 
let url = location.href; 
Copy the code

Each line in the above code uses the Location object. If you use the with statement, you can write less code:

with(location) { 
 let qs = search.substring(1); 
 let hostName = hostname; 
 let url = href; 
} 
Copy the code

Here, the with statement is used to connect the Location object. This means that inside the statement, each variable is considered a local variable first. If the local variable is not found, the Location object is searched to see if it has an attribute with the same name. If so, the variable is evaluated as a property of the Location object.

Strict mode does not allow the with statement, otherwise an error will be thrown.

Because the with statement affects performance and is difficult to debug, it is generally not recommended to use in production code.

A switch statement

The switch statement is a flow-control statement closely related to the IF statement, borrowed from other languages.

switch (expression) { 
    case value1: 
        statement 
        break; 
    case value2: 
        statement 
        break; 
    default: 
        statement 
}        
Copy the code
  • expressionExpression:
  • case(Condition/branch) : If the expression is equal to the following value, the following statement is executed.breakKeyword causes code execution to jumpswitchStatements. If there is nobreak, the code continues to match the next condition.
  • defaultThe keyword is used to specify the statement to be executed by default if none of the conditions are met(the equivalent ofelseStatement).

To avoid unnecessary condition judgments, it is best to follow each condition with a break statement. If you do need to match several conditions in a row, it is recommended to write a comment indicating that the break is deliberately ignored, as follows:

switch (i) { 
    case 25: 
    / * * / 
    case 35: 
        console.log("25 or 35"); 
        break; 
    case 45: 
        console.log("45"); 
        break; 
    default: 
        console.log("Other"); 
} 
Copy the code

Although the Switch statement is borrowed from other languages, ECMAScript gives it some unique features:

  • switchstatementsCan be used for all data types, so you can use strings or even objects.
  • The value of a condition does not need to be a constant; it can also be a variable or an expression.
  • Any expression can be a parameter to a switch/case.
let num = 25; 
switch (true) { 
    case num < 0: 
        console.log("Less than 0."); 
        break; 
    case num >= 0 && num <= 10: 
        console.log("Between 0 and 10."); 
        break; 
    case num > 10 && num <= 20: 
        console.log("Between 10 and 20."); 
        break; 
    default: 
        console.log("More than 20."); 
} 
Copy the code

The above code first defines the variable num externally, and the argument passed to the switch statement is true because each conditional expression returns a Boolean value. Conditional expressions are evaluated until an expression returns true; Otherwise, it jumps all the way to the default statement.

Note: The switch statement uses the congruent operator when comparing the value of each condition, so it does not cast the data type (for example, the string “10” does not equal the value 10).

Return statement

  • Returns the value of the function
  • The function stops execution and exits
function sum(num1, num2) { 
    return num1 + num2; 
    console.log('This code will not be executed'); The code following the return statement will not be executed
} 

const result = sum(5.10);
Copy the code

A best practice is that a function either returns a value or does not. Functions that return values only under certain conditions can be troublesome, especially when debugging.