javascript: Differences between expressions and statements [translation]_javascript techniques

Source: Internet
Author: User
1. Statements and expressions

There are differences between expressions and statements in JavaScript. An expression produces a value that can be placed anywhere that requires a value, such as an argument that is called as a function. Each of the following lines of code is an expression:

Myvar3 + xmyfunc ("A", "B") statements can be interpreted as a behavior. A loop statement and an IF statement are typical statements. A program is made up of a series of statements. Some places in JavaScript that need statements, You can use an expression instead. Such a statement is called an expression statement. But in turn, you can't: you can't put a statement in a place that requires an expression. For example, an If statement cannot be used as a parameter of a function.

2. Other grammar

Look at the following two pairs of similar syntax, understand these, can help us better understand the relationship between the statement and expression.

2.1 If statements and conditional operators
The following is an example of an if statement:

Copy Code code as follows:

var x;
if (y >= 0) {
x = y;
} else {
x =-Y;
}


An expression similar to an If statement function is called a conditional operator. The above statement is equivalent to the following.

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

The code between equals and semicolons is the conditional expression. The parentheses on either side are not required, but I think the parentheses make the conditional expression easier to read.

2.2 Semicolon and comma operators
In JavaScript, you can connect two statements by using semicolons:

Foo (); Bar () to connect two expressions, use an uncommon comma operator:

Foo (), the bar () comma operator evaluates the two expressions before and after, and then returns the evaluation of the right expression. For example:
Copy Code code as follows:

> "A", "B"
' B '

> var x = ("A", "B");
> x
' B '

> Console.log ("A", "B");



3. An expression that looks like a statement

Some of the expressions look like statements, which can cause some trouble.

3.1 Object literals and statement blocks
The following is an object literal, which is an expression that can generate an object value.
Copy Code code as follows:

{
Foo:bar (3, 5)
}

At the same time, however, it is also a perfectly valid statement, and the components of this statement are:

• A code block: A sequence of statements surrounded by braces.
• A label: You can place a label in front of any statement. Foo here is a label.
• A statement: expression statement bar (3, 5).
You might be shocked that JavaScript can have separate blocks of code (common blocks of code are based on loops or if statements). The following code demonstrates the role of this block of code: You can set a label on it and jump out of the code block.
Copy Code code as follows:

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

3.2 function expressions and function declarations
The following code is a function expression:

function () {} You can also give the expression a name and turn it into a named (not anonymous) function expression:

Functions foo () {} The Function name (foo) of this function only exists inside the function, for example, it can be used to do recursive operations:

Copy Code code as follows:

> 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 looks like it on the surface, and it doesn't make any difference to a function declaration. But their effects are different: a function expression produces a value (a function). A function declaration performs an action: assigns a function to a variable. In addition, only function expressions can be called immediately, and function declarations are not possible.

3.3 Conflict Resolution
As you can see from 3.1 and 3.2, some expressions and statements do not see any difference on the surface. It also means that the same code, appearing in the expression context and appearing in the statement context, will behave differently. In general, the two contexts do not intersect. However, if it is an expression statement, There is an overlap: that is, there are expressions that appear on the statement context. To address this ambiguity, JavaScript syntax prohibits expression statements with curly braces or keyword "function":
Copy Code code as follows:

Expressionstatement:
[lookahead∉{' {', ' function '}] Expression;

So, what if you want to write an expression that starts with those signs? You can put it inside a bracket, this does not change the result of the run, only ensures that the expression is parsed in the expression context. Let's look at two examples. The first example: eval parses its parameters according to the statement context. If you want Eval to return an object, You must add a bracket to both sides of the object literal.
Copy Code code as follows:

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

Second example: The following example is a function expression that executes immediately.
Copy Code code as follows:

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

If you omit the parentheses, you will get a syntax error (the function declaration may not be anonymous):
Copy Code code as follows:

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

If you add a function name, you will also get a syntax error (the function declaration cannot be interpreted to perform):
Copy Code code as follows:

> function foo () {return "abc"} ()
Syntaxerror:syntax Error


Another way to let an expression be parsed on the expression context is to use a unary operator, such as + or!. However, unlike using parentheses, these operators change the results of the expression. If you don't care about the result, you can use it:
Copy Code code as follows:

> +function () {console.log ("Hello")} ()
Hello
Nannan

Is the result of the + effect on the return value undefined after the function is executed.

Translator Note: I think I do not understand the translation, so the poor level to draw a picture.


Original (English): http://www.2ality.com/2012/09/expressions-vs-statements.html
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.