Chapter three Language foundation
This is the 10th day of my participation in the August More Text Challenge
Today we are going to talk about the basic statements of the language, including if,if else,switch,while, and so on. We use very little in real development, but sometimes switching methods works wonders, so we need to be as familiar with each statement as possible.
3.6 the statement
Ecma-262 describes statements (also known as flow control statements) in which most of the syntax in ECMAScript is expressed. Statements typically use one or more keywords to accomplish a given task. Statements can be simple or complex. Something as simple as telling a function to exit, or as complex as listing a bunch of instructions to execute repeatedly.
3.6.1 track if statement
The if statement is one of the most frequently used statements and has the following syntax:
if (condition) statement1 else statement2
Copy the code
The condition can be any expression, and the evaluation result is not necessarily a Boolean value. ECMAScript automatically calls the Boolean() function to convert the expression’s value to a Boolean value. If the condition evaluates to true, the statement statement1 is executed; If the condition evaluates to false, the statement statement2 is executed. The statement can be a single line of code or a block of code (that is, multiple lines of code enclosed in a pair of curly braces). Consider the following example:
if (i > 25) console.log("Greater than 25."); Else {console.log("Less than or equal to 25."); else {console.log("Less than or equal to 25."); // a statement block}Copy the code
The best practice here is to use statement blocks, even if there is only one line of code to execute. This is because block statements avoid confusion about what to execute under what conditions.
Multiple if statements can be used consecutively like this:
If (condition1) statement1 else if (condition2) statement2 else statement3 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
3.6.2 do – while statement
A do-while statement is a post-test loop in which the exit condition is evaluated only after the code in the body of the loop executes. In other words, the code in the loop executes at least once. The syntax for a do-while is as follows:
do {
statement
} while (expression);
Copy the code
Here’s an 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.
Note that post-test loops are often used in situations where the code in the loop must be executed at least once before exiting.
3.6.3 while statement
A while statement is a test-loop statement that checks the exit condition before executing the code inside the loop. Therefore, it is possible that the code in the while loop body will not execute. Here is the syntax for the while loop:
While (expression) statement // This is an example: let I = 0; while (i < 10) { i += 2; } // In this case, 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.Copy the code
3.6.4 radar echoes captured for statement
The for statement is also a first test statement, but it adds initialization code before entering the loop, and the table to be executed after the loop is executed. The syntax is as follows:
for (initialization; expression; Post-loop-expression) statement // Here is a use case: let count = 10; for (let i = 0; i < count; i++) { console.log(i); }Copy the code
The above code defines the variable I with an initial value of 0 before the loop begins. The condition expression is then evaluated, and if the result is true (I < count), the body of the loop is executed. Therefore, the body of the loop may not be executed. If the body of the loop is executed, the expression is executed after the loop to increment the variable I. The for loop is the same as the following while loop:
let count = 10;
let i = 0;
while (i < count) {
console.log(i);
i++;
}
Copy the code
Logic that cannot be implemented with a while loop cannot be implemented with a for loop. So the for loop just wraps the looping code together.
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
If only conditional expressions are included, then the for loop actually becomes the while loop:
let count = 10;
let i = 0;
for (; i < count; ) {
console.log(i);
i++;
}
Copy the code
This versatility makes the for statement widely used in the language.
3.6.5 the for in statement
A for-in statement is a strict iteration statement that enumerates non-signed key attributes in an object. The syntax is as follows:
For (const propName in window) {document.write(propName); for (const propName in window) {document.write(propName); }Copy the code
This example uses a for-in loop to display 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-in statements do not guarantee the order in which object properties 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. If the for-in loop iterates over a variable that is null or undefined, the body of the loop is not executed.
3.6.6 for – statement
A for-of statement is a strict iteration statement that iterates through the elements of an iterable. The syntax is as follows:
For (const el of [2,4,6,8]) {document.write(el); for (const el of [2,4,6,8]) {document.write(el); }Copy the code
In this example, we use a for-of statement to display all the elements in a four-element array. The loop continues until all elements have been iterated over. 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.
The for-of loop iterates over the elements in the order in which the iterable’s next() method produces the values. We’ll see more about iterables in Chapter 7
The for-of statement throws an error if the variable trying to iterate does not support iteration.
Note that ES2018 extends for-of statements by adding for-await-of loops to support asynchronous iterables that generate promises.
3.6.7 Label Statement
Label statements are used to label statements in the following syntax:
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.
3.6.8 Break and continue statements
The break and continue statements provide tighter control over the execution of loop code. The break statement is used to exit the loop immediately and force the next statement after the loop. The continue statement is also used to exit the loop immediately, but is executed again from the top of the loop. Here’s an example:
let num = 0; for (let i = 1; i < 10; i++) { if (i % 5 == 0) { break; } num++; } console.log(num); / / 4Copy the code
In the code above, the for loop increments the variable I from 1 to 10. Inside the body of the loop, there is an if statement that checks if I is divisible by 5 (using the modulo operator). If so, the break statement is executed to exit the loop. The variable num has an initial value of 0, indicating how many times the loop is executed before exiting. When the break statement is executed, the next line of code to execute is console.log(num), showing 4. The loop executes four times because the break statement causes the loop to exit when I is equal to 5, and the loop does not execute code that increments num this time. If you replace break with continue, a different effect will appear:
let num = 0; for (let i = 1; i < 10; i++) { if (i % 5 == 0) { continue; } num++; } console.log(num); / / 8Copy the code
This time, console.log shows 8, meaning that the loop has been executed in full eight times. When I is equal to 5, the loop exits before increment num, but the next iteration is performed, where I is 6. The loop then continues to its natural end, where I is equal to 10. The final value of num is 8 instead of 9 because the continue statement causes it to increment by one less time.
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) { break outermost; } num++; } } console.log(num); / / 55Copy the code
In this case, the outerMost tag identifies the first for statement. Normally, each loop is executed 10 times, which means 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 brings in a variable, the label to exit to. 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) { continue outermost; } num++; } } console.log(num); / / 95Copy 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 careful to use descriptive text for your tags and not too deeply nested.
The 3.6.9 with statement
The with statement is used to set the code scope to a specific object. The syntax is:
with (expression) statement;
Copy the code
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.
Warning The use of the with statement is generally not recommended in production code because it affects performance and is difficult to debug the code within it.
3.6.10 switch statement
The switch statement is a flow-control statement closely related to the IF statement, borrowed from other languages. The syntax of the ECMAScript switch statement is very similar to that of the C switch statement, as follows:
switch (expression) {
case value1:
statement
break;
case value2:
statement
break;
case value3:
statement
break;
case value4:
statement
break;
default:
statement
}
Copy the code
Each case (condition/branch) here is equivalent to: “If the expression is equal to the value that follows, execute the following statement.” The break keyword causes code execution to jump out of the switch statement. If there is no break, the code continues to match the next condition. The default keyword is used to specify the statement to be executed by default (equivalent to the else statement) if none of the conditions are met.
With the switch statement, developers don’t have to write code like this:
if (i == 25) {
console.log("25");
} else if (i == 35) {
console.log("35");
} else if (i == 45) {
console.log("45");
} else {
console.log("Other");
}
Copy the code
Instead, you could write:
switch (i) {
case 25:
console.log("25");
break;
case 35:
console.log("35");
break;
case 45:
console.log("45");
break;
default:
console.log("Other");
}
Copy the code
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: /* skip */ 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. First, the switch statement can be used for all data types (in many languages, it can only be used for numbers), so strings and even objects can be used. Second, the value of a condition does not need to be a constant; it can also be a variable or an expression. Look at the following example:
switch ("hello world") {
case "hello" + " world":
console.log("Greeting was found.");
break;
case "goodbye":
console.log("Closing was found.");
break;
default:
console.log("Unexpected message was found.");
}
Copy the code
This example uses a string in a switch statement. The first condition actually uses an expression that evaluates to the concatenated result of two strings. Since the concatenated result is equal to the switch parameters, console.log will print “Greeting was found.” Being able to use expressions in conditional judgments allows you to add more logic to your judgments:
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, you jump straight to the default statement (which is what happened in this example).
Note that the switch statement uses the congruence 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).