Differences in JavaScript expressions and statements

1. statements and expressions

The JavaScript expressions and statements are different. An expression produces a value that can be placed anywhere requires a value, for example, as an argument of a function call. Each of the following line of code is an expression :

myvar
3 + x
myfunc("a", "b")

Statements can be understood as a behavior loop and if statement is a typical statement. .JavaScript a program is a series of statements of some required statement where you can use an expression instead. Such a statement termed For the expression statement but not vice versa: you can not put a sentence in a place of such an expression is required, if a statement can not function as a parameter.

2. Other grammar

Consider the following two pairs of similar syntax, after they get to know them, can help us better understand the relationship between statements and expressions.

2.1 If statements and conditional operator

Here is an example of an if statement:

Copy the code
var x;
if (y >= 0) {
    x = y;
} else {
    x = -y;
}
Copy the code

Similarly if statement function expression is called the conditional operator. The above statement is equivalent to the following.

var x = (y> = 0: -y?);

In the equal sign = and the semicolon; Code is conditional expressions between both sides parentheses are not required, but I think parentheses make conditional expressions more readable.

2.2 semicolon and the comma operator

In JavaScript, use a semicolon can be connected to two statements:

foo(); bar()

To connect two expressions, using an unusual comma operator:

foo(), bar()

Before and after the comma operator will calculate two expressions, and then returns the results to the right, for example, the expression:

Copy the code
> "a", "b"
'b'

> var x = ("a", "b");
> x
'b'

> console.log(("a", "b"));
b
Copy the code

3. seemingly statement expression

Some expressions look like statements, which may cause some trouble.

3.1 object literal statement blocks and

The following is a literal objects, i.e. objects that can generate a value of the expression.

{
foo: bar(3, 5)
}

But at the same time, it is also a perfectly legitimate statement, an integral part of this statement are:

  • A code block: a sequence of statements enclosed by braces.
  • A label: You can put a label on the front of any statement here. Foo is a label .
  • A statement: expression statement bar (3, 5) .

You might be shocked that JavaScript can actually have a separate code block (common block of code is relying on the loop or if statement) The following code demonstrates the effect of this code block: you can give it a label set then out of this block.

Copy the code
function test(printTwo) {
    printing: {
        console.log("One");
        if (!printTwo) break printing;
        console.log("Two");
    }
    console.log("Three");
}

> test(false)
One
Three

> test(true)
One
Two
Three
Copy the code

3.2 function expressions and function declarations

The following code is a function expression:

function () { }

You can also give a name to the function expression, it will be transformed into a named (non-anonymous) function expression:

function foo() { }

The name of the function ( foo ) exist only within a function, for example, the recursive computation to do with it:

> var fac = function me(x) { return x <= 1 ? 1 : x * me(x-1) }
> fac(10)
3628800
> console.log(me)
ReferenceError: me is not defined

  A named function expression from the surface, and a function declaration and there is no difference but their effect is different: a functional expression produces a value (a function) declare a function to perform an action: a function assigned to a variable. In addition, the function expression can only be called immediately, it can not function declaration.

  As long as the expression syntax, script host function is considered a direct function of the amount, if nothing is added, beginning with light function, then it is considered to be a function declaration,

3.3 to resolve conflicts

3.1 and 3.2 can be seen from some expressions and statements in the face of it not tell the difference. Means that the same code appears in the expression context and appears in the context of the statement will show a different role. Typically under circumstances, these two contexts is no intersection However, if the statement is an expression, then there will be an overlay: in other words, there will be some expression appears in the context of the statement in order to solve this ambiguity, JavaScript syntax ban expression statement with braces or keywords "function" at the beginning:

ExpressionStatement :
    [lookahead ∉ {"{", "function"}] Expression ;

So, if you want to write a sentence that begins with an expression of signs, what should I do? You can put it in an internal brackets, this does not change the operating results will only ensure that the expression is parsed in the expression the context let us look at two examples in the first example:. eval context will resolve it in accordance with the parameters of the statement if you want. eval returns an object a parenthesis, you must add the object literal amount on both sides.

> eval("{ foo: 123 }")
123
> eval("({ foo: 123 })")
{ foo: 123 }

The second example: The following example is a function expression executed immediately.

> (function () { return "abc" }())
'abc'

If you omit the parentheses, you will get a syntax error (function declarations can not be anonymous):

> function () { return "abc" }()
SyntaxError: function statement requires a name

If you add the function name, you will get a syntax error (function declarations can not be understood execute):

> function foo() { return "abc" }()
SyntaxError: syntax error

Another allow expression in context expressions are parsed way is to use a unary operator, such as  +  or  ! However, the use of parentheses and different is that these operators will change the operating results of the expression. If you do not care the result, then, can use:

> +function () { console.log("hello") }()
hello
NaN

NaN is + role in the function is executed after the return value of the undefined results .

Translator's Note: I think the translation is not clear, he drew level with crude figures.

 
 
 
 
    --------------------------- II appreciated ------------------- -
 
Expressions (expressions) and statements (statements) are very common in javascript, but that these common elements, sometimes we may not be able to correctly understand its meaning and usage to be represented. This is because we always common things instinct indicates the default, so if it were born on, meaning little to consider behind represents. For example: if the condition Why have the assignment executed immediately function Why use parentheses to enclose recalls.

  Prior to distinguish between expressions and statements, we were first introduced to them:

  1. The expressions (expressions)

    Expression is constituted by the operator, and the operation result generated syntax structure. Each expression will have a value that can be placed anywhere requires a value, for example, as an argument of a function call each of the following line of code is an expression:

var a = (5 + 6) / 2; // expression: (5 + 6) / 2
var b = (function () {return 25;}) (); // expression: (function () {return 25;}) ()
foo (a * b); // expression: a * b

  2. statements (statements)

    The statement is made "; (semicolon)" separated sentence or command. If the expression at the back plus a ";" separator, which is referred to as "expression statement." It shows that "only an expression, but there is no other statement syntax elements."

var a = (5 + 6) / 2; // the entire line, the assignment statement
if (a> 12) {statements} // conditional statement
var o = {}; // assignment
(Function (obj) {obj.b = 23;}) (o || {}); // expression statements

  General javascript statements are divided into the following categories:

  (1) declaration: variable declarations and function declarations

  (2) assignment

  (3) control statements: change the order of execution is capable of producing statements, conditional statements and loop statements including, of course, the special label statement.

  (4) expression statement: These statements remove the last semicolon, are also used as an expression. Common are: Object operations (new, delete), function call (function is executed, there must be a return value) and so on.

Copy the code
var num = 9; // statement, an assignment statement
vloop: // label statement
{// In fact, there may not need braces, and here I just want to show you what this block of code structure it
     for (var i = 1; i <10; i ++) {// loop
            if (i == num) {// conditional statement
                  break vloop;
            }else{
                  whether num - 1; 
            }      
     }  
}     
console.log (num); // expression statement, output: 5 
Copy the code

  As can be seen from the above, expression statements and there is a big difference, he said expression may also constitute part of the statement, the statement that in turn can consist of executable code block. Generally only, we can directly see the difference between the two, however, some special cases the difference is not very good.

Difficult to distinguish between expressions and statements

 1. object literal and code blocks

There he = {
     a : {},
     b : "string"    
}

      The above is a simple and extremely literal object, but only from an intuitive level, we look at the code, this literal fact, with a block of code is very similar to the feeling by the statements of two labels. The complex, as well as before the last sentence in the above I lifted the example, the example code block is located below the label statement, which contains a for loop. That's when you say this by the {} building block of code it is an expression or a statement?

  2. Name the function expression

  There are three types of functions javascript: function function declaration, function expressions and function builder created.

  (1) function declaration (FD)

  function foo(){ statements; }

  (2) function expression (FE)

  var foo = function(){ statements;}

  There is also a special point: var foo = function _foo () {statements;}, this is the time, a function for internal use to name the _foo, all this time, the type known as: named function expression (NFE).

  (3) create a constructor function

  var foo = new Function(expressions);

  In fact, it says the three types of functions is not the main focus of our chapter, which is that we explore some of the differences FD and NFE only, on the back of other functions in the elaborate content I alone.

  After the FD and is not seen in the form of NFE, there are a little bit confused, NFE addition to the previously more than a var and variable names, exactly the same structure and other FD, and this is the case, it is not explained either as FD declaration , also can be used as an assignment expression of it?

  Answers to the two previous doubts

  In view of the above two comparisons confusing grammar points, javascript also recognized the lack of its own, after decisively improved, made the following statement: JavaScript syntax statements to prohibit expression braces or keywords "function" at the beginning.

Rectifies can improve the hell is going on, when you know javascript to make such a mandatory statute, suddenly wondering for the first two have the answer.

  Prior to this, we also want to mention the next three concepts: sentence context, and the context of the expression expression statement.

  Statement Context: In this environment, which this code (expressions or statements) should be understood as a statement.

  Expression context: in this environment, this code (statements or expressions) should be understood as an expression.

  Expression statement: This expression can be seen as both an expression (because it produces a value), but also can be seen as an execution statement (because it can perform certain functions, such as the implementation of a function, etc.). Expression statement can be the basis javascript chain programming.

  The above understanding this concept play a supporting role, did not deeply investigated.

 

  Before we look at those two doubts:

  The first, followed by a colon vloop braces that section of the code, which has the assignment cycle and other operations, it means it is not an expression statement, so it does not have to follow the provisions of the above. In this fact, it is just a block statement only. But for object literal terms, it is indeed a genuine expression statement, under the statute, it can only obediently do expression, can not do statement.

  The second, for NFE type function, you can declare it as a function of the statement, but it can also be seen as an expression, but in accordance with the provisions of javascript, expression statement can not begin function, all in this, NFE are certainly expressions. Of course, for FD, it is clear that this is a function declaration statement, no doubt.

  In fact, there is another method of determining, based on the context of the judgment, we said that before the use of the statement context and function context. For an expression statement, when you can not tell it is an expression or statement, you refer to the context, determine what needs to be done in this program, is variable assignment? Or statement is executed? See the front of the "=" (assignment) or with "()" (parentheses, at this time grouping symbol, which can only contain expressions), you can be sure that this is an expression context. javascript interpreter is this dry.

Copy the code
var foo = function _foo(index){ 
    the console.log ( "incoming parameter is:" + index || "null")
} (1); // Output: incoming parameter is: 1
console.log(foo);  //输出:undefined
// The context determination, "var foo =" followed by expression context, all as will be explained later automatically execute a function immediately, though not parentheses.


function foo(index){ 
    the console.log ( "incoming parameter is:" + index || "null")
} (1) // Output: 1
console.log(foo); //function foo(index){...}
// interpreter determines this context the statement, the statement is split into two stresses. The previous period as a function declaration, after a period of "(1)" as a simple grouping of statements.
Copy the code

  See above, you are not an idea, you can actually find expression statement to forcibly convert the expression!

  Conversion method:

  (1) the use of parentheses, i.e. grouping symbol (the symbol packet only expression) conversion.

Copy the code
There it;
o = eval("{obj:'this is a object'}")
console.log(o); //this is a object

o = eval("({obj:'this is a object'})")
console.log(o); //Object {obj: "this is a object"}
Copy the code

The former does not add eval parentheses, run-time is considered a statement execution, so o is assigned to a literal string; the latter is considered to be put parentheses, is considered to be executed in the context of expression, all return an object.

  (2) using the operator because javascript engines will think that it is involved in the operation must be an expression.

Copy the code
+function(index){ 
    the console.log ( "incoming parameter is:" + index || "null");
     return index;
}(1)
// output: incoming parameter is: 1
// result of the expression is: 1
Copy the code

  I also remember the above code is run through this sentence, but was less a plus sign ( "+") in front. Compare the results of the two.

Guess you like

Origin www.cnblogs.com/xianxiaoan/p/11005395.html