Home > Article > Web Front-end > Javascript core reading sentences_javascript skills
In JavaScript, expressions are phrases, and statements are whole sentences or commands. Just as English statements end with a period, JavaScript ends with a semicolon.
An expression evaluates to a value, but a statement makes something happen.
One way to "make something happen" is to evaluate an expression with side effects. Expressions with side effects, such as assignments and function calls, can be treated as separate statements. This use of expressions as statements is also called expression statements. Similar statements include declaration statements, which are used to declare new variables or define new functions.
A JavaScript program is a collection of executable statements. By default, the JavaScript interpreter executes them in order. Another way to "make something" happen is to change the default execution order of statements:
1. Conditional statement: The JavaScript interpreter can judge based on the value of an expression; whether to execute or skip these statements, such as if and switch statements.
2. Loop statement: statement that can be executed repeatedly, such as while and for statements
3. Jump statement: allows the interpreter to jump to other parts of the program to continue execution, such as break, return and throw statements
The following article will introduce various statements and their syntax in JavaScript. The chapter concludes with a summary of these statements. A javascript program is nothing more than a collection of statements separated by separation, so once you master javascript statements, you can write javascript programs.
1. Expression statement
The assignment statement is a relatively important expression statement. Its function is to change the value of a variable, just like executing an assignment statement: for example
The increment operator ( ) and decrement operator (--) are related to assignment statements. Their purpose is to change the value of a variable, just like executing an assignment statement.
delete operator is to delete the attributes of an object (or the elements of an array), so it is generally used as a statement rather than as part of a complex expression.
Function calls are another major category of expression statements, such as
Although these client-side functions are expressions, they have a certain impact on web browsers. So we think also statements, it doesn't make sense to call a function that has no side effects unless it's part of a complex expression or assignment statement, for example. It is impossible to throw away a cosine value casually;
Math.cos(x);
In contrast, to get the cosine value, you have to assign it to a variable so that the value can be used in the future:
var cx = Math.cos(x);
Remind everyone again that each line of code ends with a semicolon.
2. Compound statements and empty statements
You can use the comma operator to join several expressions together to form one expression. Similarly, JavaScript can also combine multiple statements to form a compound statement. Simply enclose multiple statements in curly braces. Therefore, the following lines of code can be treated as a single statement and used anywhere in JavaScript where a statement is desired.
There are a few things to note about statement blocks: First, statement blocks do not require semicolons. Element statements within a block must end with a semicolon, but statement blocks do not.
Second, the lines in the statement block are indented. This is not necessary, but neat indentation can make the code more readable and easier to understand.
Third, JavaScript does not have block-level scope, and variables declared in a statement block are not private to the statement block. (Refer to the first section of Chapter 3, Section 10)
The practice of merging many statements into a large statement block is very common in JavaScript programming. Similar expressions often contain subexpressions, and many JavaScripts contain other substatements. Formally speaking, JavaScript usually allows a statement block to contain one substatement. For example: the loop body of a while loop can contain only one statement. Using statement blocks, you can put any number of statements into this block, and this statement block can be used as one statement.
In JavaScript, when you want multiple statements to be used as one statement, use a matching statement instead. An empty statement is just the opposite, allowing 0 statements. An empty statement looks like this:
;//Semicolon
The JavaScript interpreter obviously does not perform any action when executing an empty statement, but practice has proven that empty statements are sometimes useful when creating a loop with an empty loop body, such as the following for loop
In this loop, all operations are completed in the expression a[i]=0, and no loop body is needed here. However, JavaScript requires that the loop body contain at least one statement, so a single semicolon is used here to represent an empty statement.
Note that the semicolon in the right parenthesis of a for loop, while loop or if statement is very inconspicuous, which is likely to cause some fatal bugs, and these bugs are difficult to locate. For example, the execution result of the following code is likely to be the effect that the author does not intend:
If you use an empty statement for a special purpose, it is best to add comments in the code to make it clearer that this empty statement is useful
3. Declaration statement
Var and function are declaration statements, which declare or define variables or functions. These statements define and assign values to identifiers (variable and function names) that can be used anywhere in the program. The declaration statement itself does nothing, but it has an important meaning: by creating variables and functions, the semantics of the code can be better organized.
The next few sections will describe the var statement and function statement, but they do not cover all the contents of variables and functions.
i.var
Thevar statement is used to declare one or more variables. Its syntax is as follows:
var name_1[ = value_1][, ..., name_n[ = value_n]]
The keyword var is followed by a list of variables to be declared. Each variable in the list can have an initialization expression, which can be used to specify its initial value. For example:
If the var statement appears in the function body, then a local variable is defined, and its scope is this function. If you use the var statement in top-level code, it declares a global variable, which is visible throughout JavaScript. It is mentioned in Chapter 3, Section 10: Global variables are attributes of the global object. Unlike other global object attributes, variables declared with var cannot be deleted through delete.
If the variable in the var statement does not specify an initialization expression, then the value of this variable is initially undefined. Therefore, the variable value before the declaration statement is undefined.
It should be noted that the var statement can also be used as a component of a for loop or a for/in loop. (The same as the variable declaration declared before the loop, the variable declared here will also be "advanced"), for example:
Note that it doesn’t matter if you declare the same variable multiple times.
ii.function
The keyword function is used to declare functions. We have already learned function expressions (4.3). Function definitions can be written in the form of statements. For example: the two definition writing methods in the sample code below:
The syntax of function declaration is as follows:
funcname is the name identifier of the function to be declared. Following the function name is the parameter list, separated by commas. When a function is called, these identifiers refer to the actual parameters passed into the function.
The function body is composed of JavaScript statements. There is no limit to the number of statements and they are enclosed in curly braces. When a function is defined, the statements in the function body are not executed, but are associated with the new function object to be executed when the function is called. Note that the curly braces in the function statement are required, which is different from the statement blocks used by while loops and other statement locks. Even if the function body has only one statement, curly braces are still needed to enclose it.
The declaration of a function usually appears at the top of the JavaScript code and can also be nested within the body of other functions. But when nested, function declarations can only appear at the top of the nested function. That is to say: function definitions cannot appear in if, while, or other statements.
Like the var statement, the variables created by the function declaration statement cannot be deleted. But these variables are not read-only and the variable values can be overwritten.
4. Conditional statement
Conditional statements are used to execute or skip certain statements by judging whether the value of the specified expression is. These statements are "decision points" of the code, sometimes called "branches." If the javascript interpreter is executed according to the "path" of the code. Conditional statements are the fork in the road. The program reaches this point and must choose a path to continue execution.
i.if statement
Theif statement is a basic control statement. To be precise, it allows the program to execute conditionally. This statement has two forms: the first is
In this form, the value of expression is judged. If it is true, the statement statement is executed. If it is false, the statement is not executed. For example,
It should be noted that the parentheses surrounding the expression in the if statement are necessary.
Javascript syntax stipulates that the if keyword and the expression with parentheses must be followed by a statement. However, you can use statement blocks to combine multiple statements into one. Therefore, the if statement looks like this:
The second form of the if statement introduces the else clause. When the value of expression is false, the else logic is executed
For example, the following code
When nesting if statements in if/else statements, care must be taken to ensure that the else statement matches the correct if statement. Consider the following code:
In this example, the inner if statement forms the clauses required by the outer if statement. However, the matching relationship between if and else is not clear (only the indentation gives a hint) and in this case, the indentation gives the wrong hint, because this is how the JavaScript interpreter understands it.
should be used
The if/else statement selects one of two branches by judging the evaluation result of an expression. What should we do when there are many branches in the code? One solution is to use an else if statement. else if is not a real javascript statement, it is just a way of writing multiple if/else statements connected together.
There is nothing special about this code. It consists of multiple if statements, and the else clause of each if statement contains another if statement. Syntactically equivalent code can be completed using a nested form of if statements, but compared to this, the else if way of writing is obviously clearer and more preferable.
iii.switch
The if statement creates a branch during program execution, and else if can be used to process multiple branches. However, when all branches depend on the value of the same expression, else if is not the best solution. In this case, it would be wasteful to repeatedly evaluate expressions in multiple if statements.
The switch statement is suitable for handling this situation. The keyword switch is followed by an expression enclosed in parentheses. This is followed by a block of code enclosed in curly braces.
However, the complete syntax of the switch statement is more complicated than this. Following the case is an expression and a colon. Case is very similar to a tag, except that the tag does not have a name.
It is only associated with the expression that follows it. When this switch statement is executed, it first calculates the value of expression, and then checks whether the expression in the case clause is the same as the value of expression. (The similarity here is compared according to the "===" operator), if the case is matched, it will execute the corresponding code. If no matching case is found, it will execute the code block in the "default:" tag. Without the "default:" tag, switch will skip all code blocks.
The switch statement is very easy to confuse. It will be clearer with an example. The switch statement below is equivalent to the if/else statement just now
It should be noted that the keyword break is used at the end of each case statement. We will introduce the break statement later. The break statement can cause the interpreter to jump out of the switch statement or loop statement. In switch, case only specifies the starting point of the code to be executed, but not the end point. If there is no break statement, the switch statement starts executing from the code at the matching case label of the value of expression, and executes subsequent statements in sequence until the end of the entire switch code block. Of course, if you use a switch statement in a function, you can use return to replace break. Both return and break are used to terminate the switch statement and will also prevent the next case statement block from continuing to execute after one case statement is executed.
The following statement is close to practice, it converts the value into a string according to its type.
The switch statement first calculates the expression after the switch keyword, and then calculates the expression after each case in order from top to bottom until the value of the case expression is equal to the value of the switch expression. Since the matching operation for each case is actually a "===" identity operator comparison instead of "==", no type conversion is performed for the matching of expressions and cases.
As mentioned earlier, if the switch expression does not match any case expression, the statement block marked with "default:" will be executed. If there is no "default:" label, the entire switch statement will be skipped. In the previous example, the "default:" tag appears at the end of the switch, after all case tags. Of course, this is the most reasonable and commonly used way of writing. In fact, the "default:" tag can be placed anywhere within the switch statement.
5. Loop.
In order to understand conditional statements, you can think of the code in JavaScript as branch paths. A looping statement is a loop in the program path that allows a part of the code to be executed repeatedly. There are four types of loop statements in JavaScript: while, do/while, for, for/in. The following sections will explain them all at once. The most commonly used loop is the traversal of array elements. (7.6 will discuss this loop and the special loop method defined using the array class in detail.)
i.while
The if statement is a basic control statement, used to select the branch statement of the execution program. Like if, the while statement is also a basic loop statement. Its syntax is as follows:
Before executing the while statement, the JavaScript interpreter first calculates the value of expression. If its value is false, the program will skip the logical statement in the loop body and execute the next statement in the program. If its value is true, the logic in the statement in the loop body is executed, and then the value of expression is calculated. The loop will continue until the value of expression is false. In other words, when the expression is true, the statement is executed in a loop. Note that using while(true) will create an infinite loop.
Generally speaking, we don’t want javascript to perform the same operation over and over again. In almost every loop, one or more variables are iterated through the loop. It is precisely because these variables are changed that the operations of the statement executed each time in the loop are also different. Moreover, if the changed variables are used in expression, the value of the expression in each loop will also be different. This is very important. The expression responsible for the initial value being true will always be true and the loop will never end. The following example shows the while loop outputting values 0-9.
It can be found that in this example, the initial value of the variable count is 0. During the loop, its value increases by 1 each time when the loop is executed ten times. The value of the expression is programmed to false, then the while will end, and the JavaScript interpreter will execute the next statement of the program. Most loops have a counter variable like count. Although variable names such as i j k are commonly used for counters, if you want to make the code more readable, you should use more specific syntax names.
ii.do/while
The do/while loop is very similar to the while loop, except that it tests the loop expression at the end of the loop instead of the top, which means that the loop body is executed at least once. The syntax of do/while loop is as follows:
The do/while loop is not as commonly used as the while loop. This is because in practice it is uncommon to want a loop to execute at least once. Below is an example of a do/while loop
printArray([1,5,2,6])
There are two syntax differences between do/while loops and ordinary while loops. First of all, the do loop requires the keyword do to mark the beginning of the loop, and the while variable to mark the end of the loop and enter the loop condition judgment; secondly, unlike the while loop, the do loop ends with a semicolon. If the body of the while loop is enclosed in curly braces, the while loop will not end with a semicolon.
iii.for
The for statement provides a more convenient loop statement control structure than while. The for statement makes some simplifications of commonly used loop patterns. Most loops have specific counter variables. Initialize this variable before the loop starts, and then check its value before each loop. Finally, the counter variable is incremented, otherwise it is modified after the loop ends and before the next judgment. In this type of loop, the three key operations of the counter are initialization, detection, and update. The for statement explicitly declares these three operations as part of the loop syntax, each using an expression to represent them. The syntax of the for statement is as follows:
The three expressions of initialize, test, and increment are separated by semicolons. They are responsible for initialization operations, loop condition judgment, and update of counter variables. Putting them on the first line of the loop makes it easier to understand what the for loop is doing, and also prevents you from forgetting to initialize or increment a counter variable.
The easiest way to explain how a for loop works is to list an equivalent while loop
In other words, the initialize expression is only executed once before the loop starts. The initialization expression should have a side effect (usually an assignment statement). JavaScript also allows initialization expressions with var variable declaration statements, so that a variable can be declared and initialized. The test expression will be executed before each loop, and the result of the expression will be judged to determine whether to execute the loop body. Before each loop, the test expression will be executed, and its result will be judged to execute the loop body. If the test result is true, the statement in the loop body will be executed. Finally, the increment expression is executed. Also to be useful, the increment expression here must also have side effects. Generally speaking, it is either an assignment expression or an expression composed of " " and "--" operators.
The while loop above can be written using a for loop
Of course, some loops are more complex and have multiple variables iterated through at once. In JavaScript, this situation must use the comma operator, which combines the initialization expression and the increment expression into one expression for use in a for loop.
So far, the loop variables in the example code have all been numbers. Numbers are of course the most commonly used, but are not required. The following code uses a for loop to traverse the table data results and return the last object in the linked list (that is, the first object that does not contain the next attribute)
It should be noted that this code does not contain the initialize expression. One and one of the three expressions in the for loop can be ignored, but the two semicolons are essential. If the test expression is omitted, it will be an infinite loop. Similar to the while(ture) type, one way to write an infinite loop is for(;;).
iiii.for/in
The for/in statement uses the for keyword, but it is a different type of loop from the regular for loop. The syntax of for/in loop is as follows
variable is usually a variable name, or it can be an expression that can produce an lvalue or a variable declared through the var statement. In short, it is a value that applies to the left side of the assignment expression. object is an expression, and the result of this expression is an object. Likewise, statement is a statement or block of statements that forms the body of a loop.
It’s very simple to iterate over array elements using a for loop
The for/in loop is used to conveniently traverse object member attributes
During the execution of the for/in statement, the JavaScript interpreter first evaluates the object expression. If the expression is null or undefined, the JavaScript interpreter will skip the loop and execute the subsequent code. If the expression is equal to a primitive value, the primitive value is converted to the corresponding waxer object (Section 3.6). Otherwise, expression itself is already an object. JavaScript will enumerate the properties of the object in sequence to execute the loop. However, before each loop, JavaScript evaluates the variable expression and assigns the property name (a string) to it.
It should be noted that as long as in a for/in loop, the value of varibale can be used as the lvalue of the assignment expression, and it can be any expression. This expression is evaluated each time through the loop, which means it may evaluate to a different value each time through the loop. For example, you can use the following code to copy all object properties into an array:
Javascript arrays are just a special kind of object, so for/in loops can enumerate data indices just like object properties. For example, if you add this code after the above code, you can enumerate data index 0,1,2:
Actually, the for/in loop will not traverse all the properties of the object, only the "enumerable" properties will be traversed (refer to 6.7). Because the built-in methods defined by the core of the JavaScript language are not "enumerable". For example, all objects have toString(), but the for/in loop does not enumerate the toString() property. In addition to built-in methods, there are many built-in object properties that are nonenumerable (nonenumberable). All properties and methods defined in the code are enumerable (we will talk about it in Section 6.7, but there are special means in ECMAScript5 to make properties non-enumerable).
Objects can inherit the properties of other objects, and the line of inherited custom properties (6.2.ii) can also be enumerated using for/in.
If the for/in loop body deletes an attribute that has not yet been enumerated, then this attribute will no longer be enumerated. If the loop body defines new properties of the object, these properties are usually not enumerated (however, some implementations of JavaScript can enumerate properties added in the loop body).
Order of attribute enumeration
The ECMAScript specification does not specify the order in which for/in loops enumerate the properties of an object. But in fact, mainstream browser manufacturers' JavaScript implementation enumerates the properties of simple objects in the order in which they are defined, with properties defined first being enumerated first. If you create an object using the form of an object literal, the properties in the literal are enumerated in the order in which they appear. (Some websites and JavaScript libraries rely on this enumeration order, and most browser manufacturers do not modify this order). In the following cases, the enumeration order depends on the specific implementation (not interactive)
1. The object inherits enumerable properties
2. Object has properties
with integer array index
3. Use delete to delete existing attributes of the object
4. Use Object.defineProperty() or similar methods to change the object properties
6. Jump
The first type of statement in JavaScript is a jump statement. From the statement understanding, it can make javascript execution jump from one position to another position.
The break statement jumps to the end of a loop or other statement. The continue statement terminates the execution of this loop and starts the execution of the next loop. Statements in JavaScript can be named or labeled, and break and continue can identify target loops or other statement labels.
The return statement allows the interpreter to jump out of the execution of the function body. And provide the return value of this call. The throw statement triggers or throws an exception. It is used together with try/catch/finally statements, which specify the code logic for handling exceptions. This is a complex jump statement. When an exception is thrown, the program will jump to the nearest closed exception star. This exception program can be in the same function or in a higher-level call stack.
Next, describe each type of jump statement
i. Tag statement
Statements can be labeled. The label consists of an identifier and a colon before the statement:
identifier:statement
By defining a label for a statement, you can reference the statement through the label name anywhere in the program. Labels can be defined for multiple statements, although they are more useful when defining labels for blocks of statements, such as loops or conditionals. By defining a label name for the loop, you can use break and continue inside the loop body to exit the loop or directly challenge the start of the next loop. break and continue are the only statements in JavaScript that can use statement labels (discussed next in this chapter). In the following example, the while loop defines a label, and the continue statement uses this label:
The indentifier used as a tag here must be a legal JavaScript identifier, not a reserved word. The namespace of a label is different from the namespace of a variable or function, so you can use the same identifier as a statement label and as a variable or function name. A statement label is defined only within the statement it acts on (or within its clauses, of course). A statement label cannot have the same name as its internal statement label, but statement labels with the same name can appear when the two codes are not nested in each other. Labeled statements can also be labeled, that is, any statement can have many labels.
ii.break
The function of using the break statement alone is to immediately exit the loop or switch statement with the most memory. Its syntax is as follows:
break;
Since it can cause loops and switch statements to exit, this form of break is only legal in such statements.
We have already seen the break statement in the switch statement example. In a loop, if you don't want to continue executing the entire loop for whatever reason, you can use break to exit early. When the loop termination condition is very complex, it is much simpler to use the break statement in the function body to implement such conditional judgments than to write the complex termination condition directly in the loop expression.
In the following example, the loop traverses the entire array elements to find a specific value. When the entire array traversal is completed, the loop exits normally. If the array element to be found is found, use the break statement to exit the loop:
JavaScript also allows the break keyword to be followed by a statement label (only identifier, no colon)
break labelname;
When break is used together with a label, the program will jump to the end of the statement block identified by the label, or directly terminate the execution of the closed statement block. A syntax error occurs when there is no enclosing statement block specifying a label for break. When using this form of break statement, the labeled statement should not be a loop or switch statement, because the break statement can "jump out" of any enclosing block of statements. The statement here can be a group of statements grouped by curly braces, using the same label to identify a group of statements.
There cannot be a line break between the break keyword and labelname. Because JavaScript can automatically complete omitted semicolons for statements, if there is a newline between the break keyword and the label, the JavaScript interpreter will think that you are using the simplest form of break without labels, so it will add a semicolon after break. .
When you want to break out of a non-nearby loop or switch statement, you will use a labeled break statement. Here is the sample code:
Finally, it should be noted that regardless of whether the break statement is labeled or not, its control cannot cross the boundaries of the function. For example: For a function definition statement with a label, you cannot use this label to jump to the outside of the function through the inside of the function.
iii.continue statement
The continue statement is very similar to the break statement, but it does not exit the loop, but instead executes the next loop. The syntax of the continue statement is as simple as the syntax of the break statement
continue;
The continue statement will also have tags
continue lebname;
Regardless of whether the continue statement has a label or not, it can only be used in the loop body. If used elsewhere, a syntax error will be reported.
When the continue statement is executed, the current loop logic is terminated, and the next loop is executed immediately. In different types of loops, the behavior of continue is also different
1. In the while loop, specifying expression at the beginning of the loop will be tested repeatedly. If the test result is true, the loop body will be executed from the beginning.
2. In the do/while loop, the execution of the program jumps to the end of the loop. At this time, the loop condition will be re-judged before continuing to the next loop.
3. In the for loop, the auto-increment expression is first calculated, and then the test expression is detected to determine whether to execute the loop body.
4. In the for/in loop, the loop begins to traverse the next attribute name, which is assigned to the specified variable.
You need to pay attention to the difference between the continue statement in the while and for loops. The while loop directly enters the next round of loop condition judgment, but the for loop first calculates the increment expression and then judges the loop condition. The previous chapter discussed the "equivalent" behavior of a for loop to a while loop. However, because continue behaves differently in these two loops, it is impossible to perfectly simulate the equivalent for loop using a while loop.
The following code shows the continue statement without a label, which skips the subsequent logic of the current loop when an error occurs
Similar to the break statement, the labeled continue statement can be used in nested loops to jump out of hierarchically nested loop body logic. Also similar to the break statement, there cannot be a newline between the continue statement and labname.
iiii.return
Recall that a function call is an expression, and all expressions have values. The return statement in a function refers to the return value after the function call. Here is the syntax of the return statement:
return expression;
The return statement can only appear in the function body. If not, a syntax error will be reported. When the return statement is executed, the function terminates execution and returns the value of expression to the calling program. For example:
If there is no return statement, the function call will only execute each statement in the function body in sequence until the end of the function, and finally return to the calling program. In this case, the result of calling the expression is undefined. The return statement often appears as the last statement in a function, but it does not necessarily mean that it must be placed at the end of the function. Even if there is a lot of code that has not been executed when the return statement is executed, the function will still return to the calling program.
The return statement can be used alone without expression. In this case, the function will also want to call the program and return undefined. For example:
iiiiii.throw statement
The so-called exception (excepion) is a signal generated when some abnormal situation or error occurs. Throwing an exception means signaling that an error or abnormal condition has occurred. Catching an exception means processing the signal and throwing an exception, which is to use a signal to notify that an error or abnormal situation has occurred. Catching an exception refers to handling this signal, that is, taking necessary measures to recover from the exception. In JavaScript, an exception is explicitly thrown when a runtime error occurs or when the program uses the throw statement. Exceptions can be caught using try/catch/finally statements, which will be introduced in detail in the next section.
The syntax of the throw statement is as follows:
The value of expression can be of any type. Can throw an array representing error codes, or a string containing an error message. When the JavaScript interpreter throws an exception, it usually uses the Eeeor type or its subtypes, but they can also be used. An error object has a familiar representation of the error type, and a message attribute used to pass the string to the constructor (see the Error class in Part 3). In the following example, an Error is thrown when the function is called with illegal parameters. Object: