javascript: The difference between an expression and a statement

Source: Internet
Author: User

javascript: The difference between an expression and a statement

JavaScript language essence:
Expressions are composed of operators, and the syntax structure that produces the results is calculated.
A program is made up of statements, which are sentences or commands separated by "; (semicolon)".
If you add a ";" delimiter after the expression, this is called an expression statement. It indicates "only expressions, not statements of other syntactic elements"

Original: http://www.2ality.com/2012/09/expressions-vs-statements.html

This article is about the very important two points of knowledge in javascript: The difference between an expression (expressions) and a statement (statements).

1. Statements and expressions

There are differences between expressions and statements in JavaScript. An expression produces a value that can be placed anywhere a value is needed, for example, as a parameter to a function call. Each of the following lines of code is an expression:

MyVar
3 + x
MyFunc ("A", "B")

A statement 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. In JavaScript, you can use an expression instead of something that requires a statement. Such statements are called expression statements. But in turn, it is not possible to: You can't put a statement in a place where you need an expression. For example, an If statement cannot be used as a parameter to a function.

2. Other syntax

Look at these two pairs of similar grammars, which can 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:

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

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

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

The code between equals sign = and semicolon is the conditional expression. The parentheses on both sides 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 using semicolons:

Foo (); Bar ()

To connect two expressions, use the uncommon comma operator:

Foo (), Bar ()

The comma operator evaluates the front and back two expressions, and then returns the result of the right expression. For example:

> "A", "B" ' B ' > var x = ("A", "B");> x ' B ' > Console.log (("A", "B"); b
3. Expressions that appear to be statements

Some 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.

{
Foo:bar (3, 5)
}

At the same time, however, it is also a fully legal statement that has the following components:

    • A block of code: A sequence of statements surrounded by curly braces.
    • A label: You can place a label in front of any statement. Foo Here is a label .
    • A statement: The 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 purpose of this block of code: You can set a tag for it and then jump out of the block of code.

function test (printtwo) {    printing: {        console.log ("one");        if (!printtwo) break printing;        Console.log ("both");    }    Console.log ("three");} > Test (FALSE) onethree> test (true) Onetwothree
3.2 function expressions and function declarations

The following code is a function expression:

function () {}

You can also give the function expression a name and turn it into a named (non-anonymous) function expression:

function foo () {}

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

> var FAC = function Me (x) {return x <= 1? 1:x * Me (x-1)}> FAC 3628800> console.log (Me) Referenceerror: Me is not defined

A named function expression appears on the surface, and there is no difference between a function declaration. But their effect is 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 allowed.

3.3 Resolving conflicts

As can be seen from 3.1 and 3.2, some expressions and statements do not appear to be different on the surface. This means that the same code, which appears in the context of the expression and appears in the context of the statement, behaves differently. Typically, the two contexts are not intersected. But, if it is an expression, There is an overlap: that is, there are some expressions that appear on the statement context. To resolve this ambiguity, the JavaScript syntax prohibits expression statements from opening with braces or keyword "function":

Expressionstatement:    [lookahead? {"{", "function"}] Expression;

So, what do you do if you want to write an expression that starts with those flags? You can put it inside a parenthesis so that it does not change the result of the run, only that the expression is parsed in the context of the expression. Let's look at two examples. The first example:eval parses its arguments according to the context of the statement . If you want eval to return an object , you must add a parenthesis to both sides of the object literal.

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

Second example: The following example is a function expression that executes immediately.

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

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

> function () {return ' abc '} () syntaxerror:function statement requires a name

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

> function foo () {return ' abc '} () Syntaxerror:syntax error

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

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

NaN is the result of the + function on the return value undefined after the function executes .

Translator: I don't think I understand, so I drew a picture with a poor level.

javascript: The difference between an expression and a 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.