JavaScript Core Language Note 5-statements

Source: Internet
Author: User
Tags cos finally block throw exception

The expression is a phrase (phrases) in JavaScript, then the statement (statements) is the JavaScript whole sentence or command, and the statement ends with a semicolon. An expression evaluates a value that the statement uses to execute to make something happen

An expression statement

Assignment statements, increment/subtract operations, delete operators remove object properties, function calls are expression statements

1 gretting = "Hello" + name; 2 i *= 3; 3 count++; 4 Delete o.x; 5 alert (greeting) 6 window.close (); 7 Math.Cos (x) 8 cs = Math.Cos (x);
Compound statements and empty statements

The comma operator joins several expressions together to form an expression, and in the same way, multiple statements can be joined together in JavaScript to form a compound statement (compound statement). Just surround them with curly braces, and the following lines of code can be used as a single statement

1 {2    x = Math.PI; 3     cx = math.cos (x); 4     console.log ("cos (x) =" CX); 5 }

Two points to be aware of:

    • A semicolon is not required at the end of a statement block. The original statement in the block must end with a semicolon
    • The indentation of a line in a statement block is not necessary, but a reasonable indentation is easier to understand
    • The statement block does not have a block-level domain name, and the variable declared in the statement block is not private to the statement block

Empty statements (statement) Allow 0 statements, and empty statements are occasionally used when an array is first initialized

1 var a = Array (a); 2 a                                           //= [undefined,,,, undefined]3<  a;     Initialize an array, note that the semicolon at the end cannot be less than 4a                                           => [0,,, 0]

In this loop, all operations are done in the expression a[i++]=0, where no loop body is required. JavaScript, however, requires at least one statement in the loop body, so only a single semicolon is used to represent an empty statement

Statement statement

Both Var and function are declarative statements, declaring that the statement itself does nothing and is used only to better organize the semantics of the Code

Var

The Var statement is used to declare one or more variables with the following usage:

1 var name_1 [= Value_1] [,..., name_n [= Value_n]]

If the Var statement appears in the function body, then it defines a local variable whose scope is the function, and if you use the VAR statement in the top-level code, it declares a global variable , which is available throughout the program

Global variables are properties of global objects. However, global variables declared through Var cannot be deleted by deleting

If the variable in the VAR statement does not specify an initialization expression, the value of the variable is initially undefined

function

The syntax for a statement of a function declaration is as follows:

1 function Fun_name ([arg1 [, arg2 [..., argn]]) {2    statements3}4  5var f = function (x) {return x+1;};        Declaring a function through Var 6 functions f (x) {return x+1;}

Conditional statement IF
1 if (expression) {2    statement3 }

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

To avoid ambiguity, it is recommended to always add curly braces to the IF statement

else if
1 if (expression) {2    statement3} else if (expression) {4     Statement 5 }
Switch
1 switch (expression) {2    statement3 }
Loop while
1 var count = 0; 2 < Ten ) {3    console.log (count); 4     count++5}
Do/while
1 function PrintArray (a) {2 var len = a.length, i = 0;3 if (len = = 0) {4 console.log (' Empty Array ');5 } else {6 Do {7 Console.log (A[i]);8} while (++i<Len);9     }Ten }
For

The order of execution for the For loop is:

    1. Initialize
    2. Test condition is true
    3. Statement

Increment

1 for (initialize; test; increment) {2    statement3 }
In most cases, the equivalent of the while loop notation:
1 Initialize; 2 While (test) {3    statement4    increment; 5 }
For/in
1 For (variable in object) {2    statement3 }

Variable is usually a variable name (or an expression), or it can be 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

During the execution of the For/in statement, the JAVASCRIPT interpreter first evaluates an object expression. If the expression is null or undefined, the interpreter skips the loop and executes subsequent code (ECMAScript 3 May throw a type error exception). If the expression equals a primitive value, the original value is converted to its corresponding wrapper object (wrapper object) Otherwise, expression itself is already an object. JavaScript iterates through enumerable object properties to execute the Loop body statement

For/in loops do not traverse all properties of an object, only properties that are "enumerable" (emumerable) are traversed. The built-in method defined by the JavaScript language core is not "enumerable", for example, all objects have a method ToString (), but the for/in loop does not enumerate the properties of ToString. There are also many built-in properties that are not enumerable (nonenumerable). All of the properties and methods defined in the code are enumerable

Order of Property enumerations

The ECMASCRIPT specification does not specify the order in which the For/in loop enumerates object properties. But in fact, the JAVASCRIPT implementations of mainstream browser vendors enumerate the properties of simple objects in the order in which they are defined

Jump

Another type of statement in JavaScript is a jump statement (jumping statement). There are usually break, continue, return, throw

Label statement

A statement can be tagged, and the label consists of an identifier and a colon before the statement:

1 indetifier:statement

The identifier must be a valid JavaScript identifier

1 mainloop:while (token! = null) {2    //Statement3    continue mainloop; 4 }
Break statement

The use of the break statement alone immediately exits the inner loop or switch statement , followed by a statement label after the break keyword, and when break and label are used, The program jumps to the end of the block of statements identified by this tag

It cannot control beyond the bounds of a function, regardless of the break statement with no label

Continue statements

Similar to break, but it does not exit the loop, but instead executes the next loop. Continue statement can only be used in the loop body, other local use will be error

In different types of loops, the behavior of continue is also different:

    • 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 adjourned from the beginning of the execution
    • In the Do/while loop, the execution of the program jumps directly to the end of the loop, where 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 that the difference between the continue statement in the while and for loop, while loop directly into the round of the loop condition judgment, but the for loop first calculate its increment expression, and then determine the loop condition, so for loop is not fully equivalent to simulate the WHI Le loop

1 the notation in the//While statement causes a dead loop and the for statement does not2 the increment expression in the//For statement is always executed to the3 var i = 0;4while (i<Ten) {5 if (I < 5) {6 continue;7     }8 Console.log (i);9 i++;Ten } One  A For (var k= 1;K < k++) { - if (K < 5) { - continue; the     } - Console.log (k); - }
Return statement
1 return expression;

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

1 function Square (x) {return x*x;} 2 Square (2)   //= 4

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

Throw statement

The so-called anomaly (Exception) is a signal generated when an abnormal condition or error occurs. Throws an exception (throw exception), which is to signal the occurrence of an error or an abnormal head. catch (catch) exception refers to the processing of this signal, that is, to take the necessary means to recover from the exception

1 throw expression;

The value of expression can be of any type. The Error type and its subtypes are usually used when the JavaScript interpreter throws an exception

1 function factorial (x) {2    //If the output parameter is illegal, an exception is thrown 3     <  0  ) throw new Error (' x cannot be a negative number '); 4   > 1 ; f*= x, x--);       5     return F; 6 }

When the exception is recruited, the JavaScript interpreter immediately stops the currently executing logic and jumps to the nearest exception handler. Abnormal MO is the program is written by the catch clause of the try/catch/finally statement, JavaScript will follow the lexical structure of the method and the call stack upward propagation

try/catch/finally statements

The TRY clause defines all the code blocks that need to be handled by the exception. After the catch clause follows, 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 available first, the TRY clause requires at least one of the two (catch/finally) to form a complete statement.

The try, catch, and finally statement blocks must all be enclosed in curly braces, even if there is only one statement

1 try {2 //Normally, the code here will be executed from the beginning to the end without any problems .3 //But sometimes an exception is recruited, either thrown directly by the throw statement, to4 //is to throw an exception indirectly by calling a method5 } catch (e) {6 If and only if the try statement block throws an exception, the code here will be executed7 //You can use local variable E to warn of references to the Error object or other values thrown8 //You can also re-throw exceptions through the throw statement9 } finally {Ten //Regardless of whether the try statement throws an exception, the logic here is always executed, and the way to terminate the TRY statement block is: One //1. Normal termination, execution of the last statement of the statement block A //2. Terminate by break, continue or return statement - //3. Throws an exception that is caught by a catch clause - //4. Throws an exception, the exception is not captured, continues to propagate upward the}

Generally speaking, JavaScript uses try/catch statements very rarely when using finally. It is common to use finally in some back-end language IO operations, such as opening a file, an exception, or the need to close the file handle after the normal execution of a try clause

Other statement types

With, debugger and use strict

With statement

The WITH statement is used to temporarily extend the scope chain with the following syntax:

1 With (object) {2    statement3 }

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 deprecated in non-strict mode. JavaScript code with a with statement is very difficult to optimize and runs slower than code that does not use the width statement

The With statement is typically used to simplify code writing when the object nesting level is deep. Like what:

1 document.forms[0].address.value = ' a '2 document.forms[0].name.value = ' B '3 document.forms[0].job.value = ' C '4 5 //equivalent to6 With (Document.forms[0]) {7 address.value = ' a '8 name.value = ' B '9 job.value = ' C 'Ten } One //Use the WITH statement to reduce the object access prefix, but you can still solve the problem without using with A //Use variable F to cache object references - var f = document.forms[0]; - f.address.value = ' a ' the f.name.value = ' B ' -F.job.value = ' C '

The scope chain is used only when the identifier is found, and when a new variable is created, it is not used

1 var d = 0; 2 var o = {a:1, b:2, c:3}; 3 4 With (o) {5   a = 2; 6    d = 17} 8 d           //= 19 o           //= = {a:2, b:2, C:3}
Debugger statements

Debugger statements do not usually do anything. When the debugger is available and running, the JAVASCRIPT interpreter will (not be required) run in debug mode. This statement is used to produce a breakpoint (breakpoint), and the JavaScript code's call stops at the breakpoint location, so you can use the debugger to go out of the current variable, the calling stack, etc.

ECMAScript 5, the debugger statement formally added to the language specification, before this point streaming browser vendors have basically been affordable

' Use strict '

' Use strict ' is a designation introduced by ECMAScript 5. Very similar statements but not, the difference is:

    • It does not contain any language keyword, and the instruction is just an expression containing a special string literal, which is an expression statement with no side effects and nothing
    • It can only appear at the beginning of the script code or before the start of the function body, any entity statement. But not necessarily in the first line of the script or function

The purpose of using the ' use strict ' directive is to demonstrate that subsequent code (in a script or function) will be parsed into strict code

Strict code execution in strict mode, strict mode of the important language of the shortcomings, and provide robust detection and enhanced security mechanisms, and the difference between the non-strict mode is as follows:

  • The use of the width statement is prohibited in strict mode
  • In strict mode, all variables are declared first, and if an undeclared variable, function, function argument, catch clause argument, or Global object's property is assigned, a reference error exception is thrown
  • In strict mode, a call to a function (not a method) in which the This value is undefined (the This value is always a global object in non-strict mode) can be used to determine whether the current JavaScript supports strict modevar hasStrictMode = (function() { "use strict"; return this === undefined }())
  • 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 (no error in non-strict mode)
  • In strict mode, code that passes in eval () cannot declare a variable or define a function in the context in which the calling program resides, and in non-strict mode you can
  • 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, both the array element and the function parameter in arguments point to a reference to the same value
  • In strict mode, when the delete operator follows an illegal identifier (variable, function, or function argument), a syntax error exception is thrown
  • Attempting to delete a non- configurable property in strict mode throws a type error exception (in non-strict mode, returns false)
  • In strict mode, it is a syntax error to define two or more attributes with the same name in an object's direct volume
  • In strict mode, there are two or more parameters with the same name in the function declaration that produce a syntax error
  • Octal integer direct amount (prefixed with 0) is not allowed in strict mode
  • In strict mode, identifiers eval and arguments as keywords, their values cannot be changed, they cannot be assigned values, and they cannot be declared as variables, function names
  • Strict mode limits the ability to detect the call stack, and in strict mode functions, Arguments.caller and Arguments.callee throw a type error exception

JavaScript Core Language Note 5-statements

Related Article

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.