Rhino Book Note (v)--statement

Source: Internet
Author: User
Tags case statement finally block terminates javascript array

One way to "make something happen" is to evaluate an expression with a side effect. Injected assignments and function calls these expressions with side-effects can be used as separate statements, and this expression is also called an expression statement (statement) as the use of a statement. Similar to the declaration statement (Declaration statement), the declaration statement is used to declare a new variable or to define a new function.

A JavaScript program is nothing more than a collection of a series of executable statements. By default, the JavaScript interpreter executes sequentially according to the order in which the statements are written. Another way to "make something happen" is to change the default order in which statements are executed.

5.1 Expression Statements

Expression statements with side effects are the simplest of the statements in JavaScript.

An assignment statement is a more important type of expression statement, such as:

    • var greeting = "Hello" + name;

The increment operator (+ +) and the decrement operator (--) are related to the assignment statement. Their role is to change the value of a variable, just like executing an assignment statement:

    • counter++;

The important role of the delete operator is to delete the properties of an object, so it is generally used as a statement rather than as part of a complex expression:

    • Delete obj.x;

A function call is another large class of expression statements, such as:

    • alert (greeting);
    • Window.close ();

Although these client function calls are expressions, they all have some impact on the Web browser, so we think they are also statements. It is meaningless to call a function without any side effects unless it is part of a complex expression or an assignment statement, for example, it is not possible to calculate a cosine value and discard it:

    • Math.Cos (x);

Instead, the cosine value is assigned to a variable so that the value can be used in the future:

    • var cx = Math.Cos (x);

5.2 Compound statements and empty statements

Using the comma operator to concatenate several expressions together to form an expression, it is also possible to combine multiple statements together in JavaScript to form a compound statement (compound statement). You only need to enclose multiple statements in curly braces.

There are a few things to note about statement blocks:

    1. A semicolon is not required at the end of a statement block. The original statement in the block must end with a semicolon, but the statement block is not required.
    2. The lines in the statement block are indented, which is not required, but a neat indentation makes the code more readable and easier to understand.
    3. JavaScript does not have a block-level scope, and the variables declared in the statement block are not private to the statement block.

5.3 Declaration Statements

Both Var and function are declaration statements that declare or define variables or functions. These statements define identifiers (variable names and function names) and assign them values, which can be used anywhere in the program.

The statement itself does nothing, but it has an important meaning by creating variables and functions to better organize the semantics of the code.

5.3.1var

The Var statement is used to declare one or more variables.

The keyword VAR follows the list of variables to be declared, and each variable in the list can have an initialization expression that specifies its initial value.

If the Var statement appears in the function body, it defines a local variable whose scope is the function.

If you use the VAR statement in the top-level code, it declares a global variable, which is visible throughout the JavaScript program.

If the variable in the VAR statement does not specify an initialization expression, the value of the variable is initially undefined. Variables are defined in the script or function that declares them, and variable declaration statements are "advanced" to the top of a script or function. But the initialized operation is also executed at the location of the original VAR statement, and the value of the variable before the statement is undefined.

It is important to note that the Var statement can also be used as part of a for loop or for/in loop (as well as a variable declaration declared outside the loop, and the variable declared here is "in advance").

5.3.2function

The keyword function is used to define a function. A function definition can also be written in the form of a statement. For example:

var function (x) {    return x + 1// assigns the expression to a variable function  f (x) {     return x + 1// statement with variable name

The syntax for a function declaration statement is as follows:

function FuncName ([Arg1, [arg2 [..., argn]]) {

Statements

}

FuncName is the identifier of the name of the function to be declared. The parentheses after the function name are the parameter list, and the parameters are separated by commas. When a function is called, these identifiers refer to the arguments of the passed-in function.

The function body is made up of JavaScript statements, and the number of statements is unlimited and enclosed in curly braces. When a function is defined, the statement in the body of the function is not executed, and it is associated with the new function object to be executed when the function is called.

function declaration statements usually appear at the top of the JavaScript code, or can be nested within other function bodies. When nested, however, a function declaration can only be present at the top of the nested function. That is, the function definition does not appear in the IF statement, while loop, or any other statement, formally due to this limitation of the position of the function declaration, the ECMAScript standard specification does not classify the function declaration as a true statement.

Although function declaration statements and function definition expressions contain the same function names, they are still different.

Both methods create a new function object, but the function name in the function declaration statement is a variable name, and the variable points to the function object. As with Var, a function in a function definition statement is explicitly "advanced" to the top of a script or function. Therefore, they are visible throughout the script and in functions.

With Var, only the variable declaration is ahead of time-the initialization of the variable is still in its original position. With function declaration statements, however, both function names and function bodies are in advance: all functions and functions nested within the script are declared before other code in the current context. That is, you can call it before declaring a JavaScript function.

As with the Var statement, the variables created by the function declaration statement cannot be deleted. However, these variables are not read-only and variable values can be overridden.

5.4 Article statements

A conditional statement determines whether certain statements are executed or skipped by judging the value of the specified expression. These statements are "decision points" of code, sometimes referred to as "branches." If the JavaScript interpreter is executed according to the code's "path", the conditional statement is the fork point on this path, and the program must select one of the paths to continue execution when it is executed here.

5.4.1if

The IF statement is a basic control statement that allows the JavaScript program to choose the execution path, or, more precisely, conditionally execute the statement, which has two forms, the first of which is:

if (expression)

Statement

In this form, the value of expression needs to be computed, and if the result is true, then the statement is executed. If the value of expression is a false value, then statement is not executed.

The second form of the IF statement introduces the ELSE clause, which executes the logic in else when the value of expression is false. Its syntax is as follows:

if (expression)

Statement1

Else

Statement2

In this code, when expression is true, Statement1 is executed, and statement2 is executed when expression is a false value.

When using an if statement in a If/else statement, care must be taken to ensure that the Else statement matches the correct if statement.

Like most programming languages, the IF, else matching rule in JavaScript is that else is always matched to the nearest if statement.

5.4.2else if

The If/else statement chooses to execute one of the two branches by judging the result of an expression.

The else if statement is not a true JavaScript statement, it is simply a idiom when multiple if/else statements are joined together.

5.4.3switch

The IF statement creates a branch during program execution and can use else if to handle multiple branches. Then, when more branches are dependent on the value of the same expression, the else if is not the best solution.

The switch statement is appropriate to handle this situation. After the keyword switch is followed by an expression enclosed in parentheses, followed by a pair of curly braces blocks of code:

switch (expression) {

Statements

}

The code block can use multiple code fragments identified by the case keyword, followed by an expression and a colon, and the case and markup language are similar, except that the markup language does not have a name, it is only associated with the expression following it.

When the switch statement is executed, it evaluates the value of expression first, and then finds whether the expression in the case clause is the same as the value of expression ("Same" here is compared by the "= = =" operator). If a matching case is found, then the code block corresponding to it will be executed. If a matching case cannot be found, then the code block in the "default:" tag will be executed. If there is no "default:" tag, the switch statement skips all of its code blocks.

It is important to note that the keyword break is used at the end of each case statement block. Of course, if you use a switch statement in a function, you can use return instead of Break,return and break both to terminate the switch statement, and to prevent a case statement block from executing after the next case statement block is executed.

The switch statement evaluates the expression after the Switch keyword, and then evaluates the expression after each case in order from top to bottom until the value of the expression that executes to the cases is equal to the value of the switch expression. Because the match operation for each case is actually the "= = =" Identity operator comparison, instead of the "= =" equality operator comparison, the match between the expression and case does not make any type conversions.

Because not all case expressions can be executed every time a switch statement is executed, you should avoid using case expressions with side effects, such as function call expressions and assignment expressions. The safest way to do this is to use a constant expression in a case expression.

5.5 Cycles

To understand conditional statements, you can think of the code in JavaScript as a branching path. A loop statement (looping statement) is a loop in the program path that allows a part of the code to be executed repeatedly.

5.5.1while

The while statement is also a basic looping statement with the following syntax:

while (expression)

Statement

Before executing the while statement, the JavaScript interpreter first calculates the value of expression, and if its value is a false value, the program skips the logical statement in the loop body and executes the next statement in the program. Conversely, if expressions expression is true, the JavaScript interpreter executes the logic in the loop body and then computes the expression's value again, and the loop continues until the value of expression is a false value.

In other words, when the expression is true, the loop executes the statement, noting that using while is creating a dead loop.

Although the loop counter uses variable names such as I, J, and K, you should use a more semantic variable name if you want to make your code more readable.

5.5.2do/while

The Do/while loop is very similar to the while loop, except that it detects loop expressions at the tail of the loop instead of the top, which means that the loop body executes at least once. The syntax for the Do/while loop is as follows:

Do

Statement

while (expression)

There is a two-point grammatical difference between the do/while loop and the normal while loop.

First, the Do loop requires that you use the keyword do to identify the beginning of the loop, use while to identify the end of the loop and enter the loop condition to judge; second, unlike the while loop, the Do loop ends with a semicolon. If the loop body of the while is enclosed in curly braces, the while loop does not end with a semicolon.

5.5.3for

The syntax for the FOR statement is as follows:

for (initialize; test; increment)

Statement

The Initialize, test, and increment three expressions are separated by semicolons, each of which is responsible for initialization operations, loop condition judgments, and update of counter variables. Placing them in the first row of the loop makes it easier to understand what the for loop is doing, and it also prevents forgetting to initialize or decrement the counter variable.

The initialize expression is executed only once before the loop begins. The initialization expression should have side effects (usually an assignment statement). JavaScript also allows the initialization of an expression with a var variable declaration statement, so that a count variable can be declared and initialized at the same time. The test expression is executed each time the loop executes, and the result of the expression is judged to determine whether the loop body is executed, and if the test evaluates to true, the statement in the loop body is executed. Finally, execute the increment expression. Similarly, for the sake of usefulness, the increment expression here must also have side effects. Generally speaking, it is not an assignment expression is an expression consisting of the "+ +" or "--" operator.

Any of the three expressions in the For loop can be ignored, but two semicolons must be small. If the test expression is omitted, then this will be a dead loop, similarly, and while (true), the other way of writing a dead loop is for (;;).

5.5.4for/in

The For/in statement also uses the FOR keyword, but it is a class of loops that are completely different from the regular for loop. The syntax for the For/in Loop statement is as follows:

For (variable in object)

Statement

Variable is usually a variable name, an expression that can produce an lvalue, or a variable declared through a var statement, which must be a value that applies to the left side of an assignment expression. object is an expression in which the expression evaluates to an object. Similarly, statement is a statement or statement block that forms the body of a loop.

During the execution of the For/in statement, the JavaScript interpreter first evaluates an object expression. If the expression is null or the UNDEFINED,JAVASCRIPT interpreter skips the loop and executes the subsequent code. If the expression equals an original value, the original value is converted to its corresponding wrapper object (wrapper object). Otherwise, expression itself is already an object. JavaScript enumerates the properties of the object in turn to perform the loop. Then, before each loop, JavaScript evaluates the value of the variable expression and assigns the property name (a string) to it.

It is important to note that as long as the value of variable in the for/in loop can be an lvalue of an assignment expression, it can be an arbitrary expression. This expression is evaluated each time the loop is evaluated, which means that the value computed for Each loop may be different.

The JavaScript array is nothing more than a special kind of object, so the for/in loop can enumerate the data group indexes just like enumeration object properties.

In fact, the for/in loop does not traverse all the properties of the object, and only the "enumerable" (enumerable) properties are traversed.

Order of Property enumerations

The ECMAScript specification does not specify the order in which the For/in loop enumerates object properties. In practice, however, the JavaScript implementations of mainstream browser vendors enumerate the properties of simple objects in the order in which they are defined, and the properties that are defined first are enumerated first. If you create an object in the form of an object's direct amount, it is enumerated in the order in which the attributes appear in the direct amount.

The order of enumerations depends on the specific implementation (and non-interactive) in the following cases:

An object inherits an enumerable property.

The object has an integer array indexed property.

Use Delete to delete an existing property of the object.

Use Object.defineproperty () or a similar method to change the properties of an object.

Inheritance properties, except for all non-inherited "own" properties, are often enumerable and can be enumerated in the order in which they are defined. If an object property is inherited from more than one prototype (prototype), i.e. it has multiple objects on its prototype chain, then the traversal of the properties of each prototype object above the chain is performed in a particular order. Some, but not all, JavaScript implementations enumerate array properties in numerical order, rather than in a particular order. However, when the index of an array element is non-numeric or the array is a sparse array (the array index is discontinuous), they are enumerated in a particular order.

5.6 Jump

Another type of statement in JavaScript is a jump statement (jumping statement). As you can see from the name, it allows JavaScript execution to jump from one location to another.

5.6.1 Label Statements

A statement is a label that can be tagged when it consists of an identifier and a colon before the statement:

Identifier:statement

By defining a label for a statement, you can refer to the statement anywhere in the program by tag name.

By defining a tag name for the loop, you can use break and continue inside the loop body to exit the loop or jump directly to the beginning of the next loop. Break and continue are the only statements in JavaScript that can use statement labels.

5.6.2break statements

The use of the break statement alone immediately exits the inner loop or switch statement. Its syntax is as follows:

Break

Because it enables loops and switch statements to exit, this form of break is only legal if it appears in such statements.

JavaScript also allows the break keyword to follow a statement label (only identifiers, no colons):

Break LabelName;

When break and tag are used, the program jumps to the end of the block of statements identified by the tag, or terminates the execution of the closed statement block directly. A syntax error occurs when there are no closed statement blocks that specify the label to use for break.

There is no line break between the keyword breaks and labelname. Because JavaScript can give the statement auto-fill the whole province slightly off the semicolon, if the break keyword and the label has a newline, the JavaScript interpreter will assume that you are using the cut without the simplest form of the label, and therefore will fill the full number after break.

A tagged break statement is used when you want to jump out of a non-nearest loop body or switch statement by breaking.

Finally, it is important to note that the break statement does not have control over the bounds of the function, regardless of the tag.

5.6.3continue statements

The continue statement is very similar to the break statement, but it does not exit the loop, but instead executes the next loop.

Regardless of the continue statement, it can only be used in the loop body. Use in other places will report a syntax error.

When executing to the Continue statement, the current loop logic is terminated, the next loop is executed randomly, and the behavior of the continue differs in different types of loops:

    • In the while loop, the expression specified at the beginning of the loop is repeated, and if the test result is true, the loop is executed from the beginning.
    • In the Do/while loop, the execution of the program jumps directly to the end of the loop, when the loop condition is re-judged before the next loop is resumed.
    • In the For loop, the self-increment expression is evaluated first, and then the test expression is detected again to determine whether the loop body is executed.
    • In the for/in loop, the loop begins to traverse the next property name, which is assigned to the specified variable.

Note the difference between the continue statement in the while and for loop, while the loop goes directly to the next round of the loop condition, but the for loop evaluates its increment expression first and then determines the loop condition.

Because continue behaves differently in both loops, it is not possible to use a while loop to simulate an equivalent for loop perfectly.

5.6.4return statements

A function call is an expression, and all expressions have values. The return statement in the function is both the returned value after the function call is specified. Use of the return statement:

return expression;

The return statement can only appear in the function body, and if not, it will report a syntax error. When executed to the return statement, the function terminates execution and returns the value of expression to the calling program.

If there is no return statement, the function call executes each statement in the function body only sequentially until the function ends and returns to the calling program. In this case, the result of the invocation expression is undefined.

The return statement often appears as the last statement within the function, but not necessarily at the end of the function, even though many subsequent code is not specified when executing the return statement, and the function also returns the calling program.

The return statement can be used alone without having expression, so that the function returns undefined to the calling program.

Because JavaScript can automatically insert a semicolon, there cannot be a line break between the return keyword and the expression following it.

5.6.5throw statements

The so-called anomaly (Exception) is a signal that arises when an abnormal condition or error occurs. Throwing an exception is a signal that an error or exception has occurred. Catching an exception is the process of processing the signal, which is to take the necessary means to recover from the exception.

In JavaScript, exceptions are explicitly thrown when a run-time error is generated or when a program uses a throw statement. Use the try/catch/finally statement to catch exceptions.

The syntax for the throw statement is as follows:

throw expression;

The value of expression can be of any type. You can throw a number that represents an error code, or a string that contains a readable error message.

When the JavaScript interpreter throws an exception, it usually takes the error type and its subtypes, and of course it can use them. An Error object has a Name property that represents the fault type, and a message property is used to hold the string passed to the constructor.

When an exception is thrown, the JavaScript interpreter immediately stops the currently executing logic and jumps to the nearest exception handler.

5.6.6tyr/catch/finally statements

The try/catch/finally statement is a JavaScript exception handling mechanism.

Where the TRY clause defines the code block where the exception is to be handled. After the catch clause follows the TRY clause, the code logic inside the catch is called when an exception occurs somewhere inside the try block. The catch clause follows the finally block, where the cleanup code is placed, regardless of whether an exception is generated in the try block, and the logic in the finally block is always executed.

Although both catch and finally are optional, a try clause requires at least one of the two to form a complete statement. The try, catch, and finally statement blocks all need to be enclosed in curly braces, where the curly braces are required, and the curly braces cannot be omitted even if the subordinate clause has only one statement.

The keyword catch follows a pair of parentheses, which is an identifier inside the parentheses. This identifier is similar to the function parameter. When an exception is caught, the value associated with the exception (such as the Error object) is assigned to the parameter. Unlike a normal variable, the identifier in this catch clause has a block-level scope, which is defined only within the CATCH statement block.

Finally

Although finally is not used as often as catch, it is sometimes very useful. Then, we need to explain its behavior in more detail.

The FINALLY clause executes regardless of how much code in the TRY statement block is executed, as long as a part of the code in the Try statement executes. It is usually used for cleanup work after the code in the TRY clause.

Typically, the interpreter executes to the end of the try block, and then begins to execute the logic in finally to make the necessary cleanup work. When a return, continue, or break statement causes the interpreter to jump out of a try statement block, the interpreter executes the logic in the finally block before executing the new target code.

If an exception is created in a try and there is a catch clause associated with it to handle the exception, the interpreter first executes the logic in the catch and then executes the logic in the finally. If there is no local catch clause that handles the exception, the interpreter first executes the logic in the finally and then propagates the exception up until it finds a catch clause that can handle the exception.

If the finally block uses a return, continue, break, or throw statement to cause a program to jump, or changes the program execution process by calling the method that throws the exception, the interpreter ignores the jump, whether it suspends the program or continues execution.

In the absence of a catch clause, the TRY clause can be used in conjunction with the finally clause. In this case, the finally block contains only the cleanup code, which is bound to be executed regardless of whether there is a break, continue, or return statement in the try block.

5.7 Other statement types

5.7.1with statements

Scope chain, a list of objects that can be retrieved sequentially, through which variable name resolution can be performed.

The WITH statement is used to temporarily extend the scope chain, which has the following syntax:

With (object)

Statement

This statement adds an object to the head of the scope chain, executes the statement, and finally restores the scope chain to its original state.

With statements are forbidden in strict mode, and with statements are not recommended in non-strict mode, avoid using with statements whenever possible.

5.7.2debugger statements

Debugger statements do not usually do anything. Then, when the debugger is available and running, the JavaScript interpreter will (not be required) run in debug mode. In fact, this statement is used to produce a breakpoint (breakpoint), where the execution of the JavaScript code stops at the breakpoint, and the debugger outputs the value of the variable, checks the call stack, and so on.

In ECMAScript5, debugger statements are formally added to the language. Note that the available debuggers are far from enough, and the debugger statement does not start the debugger. But if the debugger is already running, this statement will actually produce a breakpoint.

5.7.3 "Use strict"

"Use strict" is an instruction introduced by ECMASCRIPT5. Directive is not a statement.

There are two important differences between the "use strict" directive and the normal statement:

It does not contain any language keyword, and the instruction is simply an expression that contains the direct amount of a special string (either using single quotes or double quotes), and for JavaScript interpreters that do not implement ECMASCRIPT5, it is simply an expression statement with no side effect. It didn't do anything.

It can only appear at the beginning of the script code or before the start of the function body, any entity statement. However, it does not necessarily appear in the first line of the script or in the first line of the function body, because there may be other string direct expression statements after or before the "use strict" instruction, and the specific implementation of JavaScript may parse them into the interpreter's own instructions. After the first regular statement in a script or function, the string direct expression statements are treated as normal expression statements, and they are not interpreted as instructions, nor do they have any side effects.

The purpose of using the "use strict" directive is to demonstrate that subsequent code (in a script or function) will be parsed into a strict code (strict). If the code in the top layer (not in any function) uses the "Use strict" directive, then they are strictly code. If the code of the function body is also strict code. The code in eval () is a strict code if the code in the eval () call is in strict code or eval () uses the "Script code" directive in the string to execute.

Strict code executes in strict mode. The strict pattern in ECMAScript5 is a restricted subset of the language, which corrects important flaws in the language and provides robust error detection and enhanced security mechanisms. The difference between strict and non-strict modes is as follows (the first three is particularly important):

  • The WITH statement is forbidden in strict mode.
  • In strict mode, all variables are declared first, and if you assign a value to an undeclared variable, function, function argument, catch clause argument, or Global object, a reference error exception is thrown (in non-strict mode, the method of implicitly declaring a global variable is to add a new property to the global object).
  • In strict mode, a call to a function (not a method) in one of the this value is undefined. (in non-strict mode, this method of implicitly declaring a global variable is to add a new property to the global object). This feature can be used to determine whether the JavaScript implementation supports strict mode.
  • Similarly, in strict mode, when a function is called through call () or apply (), the This value is the first parameter passed in by calling () or apply (in non-strict mode, Null and undefined values are replaced by global objects and non-object values that are converted to objects.
  • In strict mode, assigning a value to a read-only property and creating a new member for a non-extensible object throws a type error exception (in non-strict mode, these operations simply fail with no error).
  • In strict mode, the code passed in to eval () cannot declare a variable or define a function in the context in which the calling program is located, and in non-strict mode you can do so. Instead, variables and functions are defined in the new scope created by Eval (), which is deprecated when eval () returns.
  • In strict mode, the arguments object in the function has a static copy of the value passed in to the function. In non-strict mode, the arguments object has a "magic" behavior, and the array elements and function parameters in the arguments are references to the same value.
  • In strict mode, when the delete operator follows an illegal identifier (such as a variable, function, function argument), a syntax error exception is thrown (in non-strict mode, the delete expression does nothing and returns false).
  • In strict mode, attempting to delete a non-configurable property throws a type error exception (in non-strict mode, the delete expression operation fails and returns false).
  • In strict mode, defining two or more attributes with the same name in an object's direct volume will result in a syntax error (no error in non-strict mode).
  • In strict mode, there are two or more parameters with the same name in the function declaration that produce a syntax error (no error in non-strict mode).
  • In strict mode, the direct amount of octal integers (prefixed with 0 instead of 0x) is not allowed (some implementations in non-strict mode allow octal integers directly).
  • In strict mode, identifiers eval and arguments are used as keywords, and their values cannot be changed. These identifiers cannot be assigned values, nor can they be declared as variables, used as function names, as function arguments, or as identifiers for catch blocks.
  • The ability to detect the call stack is limited in strict mode, and Arguments.caller and Arguments.callee throw a type error exception in the strict mode function. Strict-mode functions also have the caller and arguments properties, which throw a type-error exception when accessing both properties (some JavaScript implementations define these nonstandard attributes in non-strict mode).

Rhino Book Note (v)--statement

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.