In JavaScript: Differences Between Expressions and statements [translate] _ javascript tips-js tutorial

Source: Internet
Author: User
This article describes two important knowledge points in JavaScript: expressions and statements. 1. statements and expressions

Expressions in JavaScript are different from statements. an expression generates a value, which can be placed wherever a value is needed, for example, as a function call parameter. each line of code below is an expression:

The myvar3 + xmyfunc ("a", "B") statement can be understood as an action. loop statements and if statements are typical statements. A program is composed of a series of statements. in JavaScript, you can use an expression instead of a statement. such a statement is called an expression statement. but the opposite is not true: you cannot place a statement where an expression is needed. for example, an if statement cannot be used as a function parameter.

2. Other syntaxes

The following two similar syntaxes help us better understand the relationship between statements and expressions.

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

The Code is as follows:


Var x;
If (y> = 0 ){
X = y;
} Else {
X =-y;
}



The expression similar to the if statement function is called a conditional operator. The preceding statement is equivalent to the following.

Var x = (y> = 0? Y:-y );

The code between equal sign = and Semicolon is a conditional expression. Parentheses on both sides are not required, but I think parentheses make conditional expressions easier to read.

2.2 semicolon and comma Operator
In JavaScript, you can use a semicolon to connect two statements:

Foo (); bar () is an uncommon comma operator to connect two expressions:

The foo (), bar () comma operator calculates the first and second expressions, and then returns the calculation result of the right expression. For example:

The Code is as follows:


> "A", "B"
'B'

> Var x = ("a", "B ");
> X
'B'

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



3. Seemingly statement expressions

Some Expressions seem like statements, which may cause some trouble.

3.1 object literal volume and statement Block
The following is an object literal, that is, an expression that can generate an object value.

The Code is as follows:


{
Foo: bar (3, 5)
}


However, it is also a completely legal statement, which consists of the following parts:

• A code block: a sequence of statements surrounded by braces.
• One Tag: You can place a tag before any statement. foo is a tag.
• One Statement: expression statement bar (3, 5 ).
You may be shocked, that is, JavaScript can have independent code blocks (common code blocks rely on loops or if statements ). the following code demonstrates the function of this code block: you can set a tag for it and then jump out of this code block.

The Code is 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 name this function expression and convert it into a named (non-Anonymous) function expression:

Function foo () {} the function name (foo) of this function only exists in the function. For example, you can use it for Recursive operations:

The Code is 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 a function declaration. however, their effects are different: A function expression generates a value (a function ). A function declaration executes an action: assign a function to a variable. in addition, only function expressions can be called immediately, and function declaration is not allowed.

3.3 conflict resolution
We can see from 3.1 and 3.2 that some expressions and statements have no difference on the surface. this means that the same code appears in the expression context and in the statement context. normally, the two contexts have no intersection. however, for expression statements, there is an overlap: that is, some expressions appear in the statement context. to solve this ambiguity, JavaScript syntax disables expression statements starting with braces or the keyword "function:

The Code is as follows:


ExpressionStatement:
[Lookahead detail {"{", "function"}] Expression;


So what if you want to write an expression statement that starts with the mark? You can put it inside a bracket. This does not change the running result, but only ensures that the expression is parsed in the context of the expression. let's look at two examples. example 1: eval parses its parameters according to the context of the statement. if you want eval to return an object, you must add a bracket on both sides of the object literal.

The Code is as follows:


> Eval ("{foo: 123 }")
123
> Eval ("({foo: 123 })")
{Foo: 123}


Example 2: The following example shows a function expression for immediate execution.

The Code is as follows:


> (Function () {return "abc "}())
'Abc'


If you omit the parentheses, you will get a syntax error (the function declaration cannot be anonymous ):

The Code is as follows:


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


If you add the function name, you will also get a syntax error (the function declaration cannot be understood for execution ):

The Code is as follows:


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



Another way to parse the expression context is to use the unary operator, such as + or !. However, unlike brackets, these operators change the running results of expressions. If you do not care about the results, you can use the following operators:

The Code is as follows:


> + Function () {console. log ("hello ")}()
Hello
NaNNaN


Yes + is the result of the returned value undefined after function execution.

Note: I do not understand the translation, so I drew a picture with a poor level.


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