javascript: The difference between an expression and a statement

Source: Internet
Author: User
Tags types of functions

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:

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");        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:

return x <= 1? 1:x * Me (x-1)}> FAC (Ten) 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 , the function declaration is not possible.

  As long as it is an expression syntax, the script host thinks that function is a direct function, and if nothing is added, the light begins with a function and is considered a declaration of functions.

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, theJavaScript 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 in the context of a statement . If you want eval to return an object , you must add a parenthesis to the object literal .

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

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

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

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

Return "ABC"Function statement requires a name

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

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.

---------------------------Second understanding of--------------------Expressions (expressions) and statements (statements) are very common in JavaScript, but these are common elements, and sometimes we may not be able to correctly grasp the meaning and usage of their representations. This is because we always have the instinct to express the common things by default, as if it were born to do so, and seldom consider the meaning behind it. For example, if the condition of the if can have an assignment, the immediate execution of the function with parentheses to enclose the call and so on.

Before we differentiate between expressions and statements, we'll introduce them separately:

1. Expression (expressions)

Expressions are composed of operators, and the syntax structure that produces the results is calculated. Each expression produces a value that can be placed anywhere a value is needed, for example, as a parameter of a function call. Each of the following lines of code is an expression:

var a = (5 + 6)/2; Expression: (5 + 6)/2var B = (function () {return 25;}) (); Expression: (function () {return 25;}) () foo (a*b); Expression: a*b
2. Statement (statements)

A statement is a sentence or command delimited 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."

var a = (5 + 6)/2; Entire row, assignment statement if (A>12) {statements}//conditional statement var o = {}; Assignment statement (function (obj) {obj.b = 23;}) (o| | {}); An expression statement

The general JavaScript statements are divided into the following categories:

(1) Declaration statement: Variable declaration and function declaration

(2) Assignment statement

(3) Control statements: Ability to change the order of execution of statements, including conditional statements and loop statements, and of course, more special label statements.

(4) Expression statements: These statements remove the last semicolon, and can also be used when an expression. Common are: Object operations (new, delete), function calls (function execution, must have return values), and so on.

var num = 9; Declaration, assignment Statement vloop://Tag Statement {//    in fact here curly braces can not be needed, here I just want to show you this code block structure for     (var i=1; i<10; i++) {//Loop statement            if (i= =num) {//Conditional statement break                  Vloop;            } else{                  num = num-1;     }}} Console.log (num); Expression statement, Output: 5

As can be seen above, expressions and statements are still very different, can also say that the expression is the constituent part of the statement, and the statement can be composed of executable code block. Generally, we can see the difference between the two very intuitively, but some special cases are not very good differences.

Hard-to-distinguish expressions and statements 1. Object literals and code blocks
var o = {     A: {},     B: ' String '    }

The above is a very simple object literal, but from the intuitive level of the code, this literal is actually very similar to the code block, composed of two tag statements. More complicated, and before I put that example in the statement at the end of the sentence, the code block in the example is below the label statement, which contains a for loop. At this point, do you say that the block of code built by {} is an expression or a statement?

2. Named function expressions

There are three types of functions in javascript: function declarations, function expressions, and functions created by function constructors.

(1) function declaration (FD)

function foo () {statements;}

(2) function expression (FE)

var foo = function () {statements;}

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

(3) Function Builder creation

var foo = new Function (expressions);

In fact, it said that the three types of functions are not the main focus of our chapter, which we also explore some of the differences between FD and NFE, about the other functions of the content I am alone in detail.

is not to see FD and NFE form, and a little bit confused, NFE in addition to a VAR and variable name in front of the other, and the structure of FD is the same, so that is not to say that FD can be both a declaration statement, but also can be used as an assignment expression?

Answer the previous two doubts

Given the two confusing grammatical points above, JavaScript itself recognizes the inadequacy and then decisively improves it, making the following statement: TheJavaScript syntax prohibits an expression statement from opening with braces or keyword "function."

Knowing how to make mistakes can improve, and when you know that JavaScript is making such a mandatory statute, you have an answer to the first two doubts.

Before that, we would like to mention three concepts: the statement context, the expression context, and the expression statement.

Statement context: In this context, this code (an expression or a statement) should be interpreted as a statement.

Expression context: In this context, the code (expression or statement) should be interpreted as an expression.

Expression statement: This expression can be thought of as an expression (because it can produce a value) and as an execution statement (because it can perform certain functions, such as executing a function, etc.). Expression statements can be the basis for JavaScript-chained programming.

The above concept plays an auxiliary role in understanding and does not have to be pursued deeply.

Let's look at the two previous doubts:

First, the Vloop Colon is followed by a section of code in curly braces that has loops and assignments, which means that it is not an expression statement, so it does not have to follow the above rules. In fact it's just a code block statement. But for the object literal, it really is a real expression statement, according to the statute, it can only obediently do the expression, can not make statements.

Second, for the NFE type function, you can view it as a function declaration statement, but also as an expression, but according to JavaScript, expression statements cannot begin with a function, all of which, in NFE, are definitely expressions. Of course, for FD, this is obviously a function declaration statement, no doubt.

In fact, there is another way of judging, judging by context, using the statement context and the function context that we used to say. For an expression statement, when you cannot tell whether it is an expression or a statement, you refer to the context and determine what the program needs to do in this case, which is the variable assignment? or statement execution? You can be sure that this is an expression context when you see the preceding by "=" (Assignment) or with "()" (parentheses, where the group character contains only the expression). The JavaScript interpreter is the one who did it.

var foo = function _foo (index) {     Console.log ("passed in parameter is:" +index| | " Null value ")} (1);  Output: The parameters passed in are: 1console.log (foo);  Output: undefined//According to the context, "var foo =" is followed by an expression context, and all the interpreters automatically take the following as an immediate execution function, although there are no parentheses. function foo (index) {     Console.log ("passed in parameter is:" +index| | " Null value ")} (1)    //output: 1console.log (foo);//function foo (index) {...} The interpreter determines that this is a statement context, so the statement is split into two paragraphs. The previous paragraph is a function declaration, and the latter section "(1)" is a simple grouping statement.

See above, you are not brainwave, and found that you can actually force the expression statement to be converted into an expression!

Conversion method:

(1) The use of parentheses, which is the grouping symbol (only allowed in the group character), to convert.

var o;o = eval ("{obj: ' This is a object '}") Console.log (o); This was a objecto = eval ("({obj: ' This is a object '})" Console.log (o); object {obj: "This is a object"}

The former does not have parentheses in the eval, the runtime is considered to be a statement execution, so O is assigned a literal string, and the latter, which is considered to be a parenthesis, is considered to be executed in the context of an expression, all returning an object.

(2) The operator is used because the JavaScript engine thinks it must be an expression to participate in the operation.

+function (index) {     Console.log ("passed in parameter is:" +index| | " Null value ");     return index;} (1)//output: The parameter passed is: 1//expression result is: 1

I remember that I ran this code, but there was a plus sign ("+") in front of me. Compare the results of both.

javascript: The difference between an expression and a statement

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.