JavaScript: 语句和表达式的区别?

我之前问了 这个一个问题,在对这个话题进行了更多的思考之后,我开始思考术语“陈述”和“表达”之间看似模糊的界限在哪里。所有的语句都是表达式吗?REPL 控制台中的返回值来自哪里?它们似乎并不总是有任何直观的意义。当然,如果键入 1+1,就会得到 2,但是其他时候逻辑是什么并不那么明显。

假设输入到 REPL 中的任何东西都会产生 一些值,这是否意味着它可以在 JS 源代码中作为表达式和独立语句使用?

下面代码片段中可用于 _X_的代码字符串是否也可用于 _Y_,反之亦然?if(_X_) _Y_

51281 次浏览

Are all statements also expressions?

“Wherever JavaScript expects a statement, you can also write an expression. Such a statement is called an expression statement. The reverse does not hold: you cannot write a statement where JavaScript expects an expression. For example, an if statement cannot become the argument of a function.”

This is comes from a recent post by Axel Rauschmayer about this topic: Expressions versus statements in JavaScript

Hope it helps.

Expression produces or evaluates some value.

Examples of expressions: new Date() produces new Date object without any side effect. [1,2,3] produces a new array without any side effect. 5+6 produces a new value 11.It just produces new value without any side effect.

Statement produces some behavior or does something and it has some side effect also. Based on the side effect, statements can be categorized.

x=5; is a statement and here side effect is assignment or change in x.

setTimeout() - start of timer is the side effect.

Statements are generally separated by semicolon.

Expression statement are the expression that has some side effect or simply "expression with side effect".

Examples of expression statement:

x+=6; is the complex expression(group of primary expressions) is doing assignment that is a side effect, so called expression statement.

delete a[2];

According to MDN:

An expression is any valid unit of code that resolves to a value.

As such, anything that can be used as an rvalue is an expression.

The criterion is not whether side effects exist. Expressions can definitely have side effects. E.g. a=2 is an expression as it has a value (2) and also assigns a value to a variable. Which is why you can do things like:

let a;
let b = 1 + (a = 2); // a is now 2 and b is 3

It is possible for the same (textual) block of code to be considered both an expression and a statement depending on the context. E.g. the text snippet function f(){} is an expression on line 1 and a statement in line 2 in the below code:

let g = function f() {};
function f() {};

So whether something is an expression or a statement cannot (in the general case) be determined by looking at a textual piece of code out of context; rather it is a property of a node in a syntax tree and can be decided only after the code is (mentally or actually) parsed.

Also, and perhaps more importantly, function statements (a.k.a function declarations) inside a function f form part of the execution context that gets created when function f is invoked. However, function expressions do not form part of that execution context.

One often quoted effect of that is that function declarations get "hoisted" whereas function expressions do not.

A more subtle effect can also be experimentally observed in deep recursions given that function statements take up space in the execution context whereas function expressions do not. E.g. the below code uses infinite recursion of a function f. Function f in the first case includes a function expression inside it, in the second case it includes the equivalent function declaration:

// Function Expression
{
let i = 0;
try {


function f () {
i++;
(function g() {})(); // this is an expression
f();
}


f();


} catch (err) {
console.log(`Function Expressions case: depth of ${i} reached. Error: ${err.name}`);
}
}
// Function Declaration
{
let i = 0;
try {
function f () {
i++;
function g() {}; // this is a statement
g();
f();
}


f();


} catch (err) {
console.log(`Functions Declarations case: depth of ${i} reached. Error: ${err.name}`);
}
}

On my machine I consistently get the following (in node.js):

Function Expressions case: depth of 17687 reached. Error: RangeError
Functions Declarations case: depth of 15476 reached. Error: RangeError

… which is consistent with the fact that Function Declarations increase the amount of space necessary to hold an execution context and thus eat up stack space a little faster and so slightly decrease the maximum recursion depth.

At its simplest terms, expressions are evaluated to produce a value. On the other hand, statements are executed to make something happen.

We have the following two types of expressions:

1. Boolean expression is uses to execute block of statements. enter image description here

2. Arithmetic expression is uses for variable assignments, which acts as a statements too.

For example: number = number + 1;

All programs in JavaScript are made of statements and they end with semicolons, except block statements which is used to group zero or more statements. Statements are just perform some actions but do not produce any value or output whereas expressions return some value. When interpreter sees an expression it retrieves its value and replaces expression with new value. Statements are used to manipulate those expressions. You can check whether it's an expresion or a statement here : JavaScript Parser

Expression: a unit of code that resolves to a value, as instance, literals & operators. Examples for expressions:

> 3
> 1 + 2
> "expression"
> fn()
> []
> {}


Statement: a unit of code representing one instruction or more, usually starts with a language reserved keyword and ends, explicitly or implicitly, with a statement terminator. Examples of statements:

> 3;
> let x = 3;
> if () {}
> for () {}
> while () {}

I highly recommend reading Dr. Axel Rauschmayer's comprehensive blog post
Expressions versus statements in JavaScript
as mentioned in @ZER0's accepted answer above.

But my favorite memory shortcut is:

Expression:
e can be set Equal to an Expression
..orExpressed by printing it.
Statement:
..anything else.


The following is modified from
Anders Kaseorg's Quora answer.

A statement is a complete line of code that performs some action.

Every Expression can be used as a statement
(whose effect is to evaluate the expression, and ignore the resulting value).

But an Expression is any section of the code that evaluates to a value.

Expressions can be combined “horizontally” into larger expressions using operators.
E has a horizontally flat top

Most statements cannot be used as expressions.

Statements can only be combined “vertically” by writing one after another, or with block constructs.
S runs vertically in comparison.


From Quora Post by Ryan Lam:

Here’s a general rule of thumb: If you can print it, or assign it to a variable, it’s an expression. If you can’t, it’s a statement.

Here are some examples of expressions:

2 + 2
3 * 7
1 + 2 + 3 * (8 ** 9) - sqrt(4.0)
min(2, 22)
max(3, 94)
round(81.5)
"foo"
"bar"
"foo" + "bar"
None
True
False
2
3
4.0

All of the above can be printed or assigned to a variable.

Here are some examples of statements:

if CONDITION:
elif CONDITION:
else:
for VARIABLE in SEQUENCE:
while CONDITION:
try:
except EXCEPTION as e:
class MYCLASS:
def MYFUNCTION():
return SOMETHING
raise SOMETHING
with SOMETHING:

None of the above constructs can be assigned to a variable. They are syntactic elements that serve a purpose, but do not themselves have any intrinsic “value”. In other words, these constructs don’t “evaluate” to anything. Trying to do any of the following, for example, would be absurd, and simply wouldn’t work:

x = if CONDITION:
y = while CONDITION:
z = return 42
foo = for i in range(10):

A fragment of code that produces a value is called an expression. Every value that is written literally (such as 22 or "psychoanalysis") is an expression. An expression between parentheses is also an expression, as is a binary operator applied to two expressions or a unary operator applied to one.

An expression corresponds to a sentence fragment in human language, a JavaScript statement corresponds to a full sentence. A program is a list of statements.

The simplest kind of statement is an expression with a semicolon after it. This is a program:

1; !false; It is a useless program, though. An expression can be content to just produce a value, which can then be used by the enclosing code. A statement stands on its own, so it amounts to something only if it affects the world.

Statement could have side effects.

https://eloquentjavascript.net/02_program_structure.html

Go to browser console ( Ctrl + Shift + I or Command + Shift + I ) :

Enter code which is ambiguous to you.

If the browser returns undefined after each line of execution, its a statement (except expressions which actually return undefined as a result)

If the browser returns any value other than undefined after each line of execution, its an expression.

Chrome browser console image showing differences between expression and statement

The browser console acts as though it uses console.log(statement) for every line of code entered. Refer this for more info.

This procedure is only to verify.

But its necessary to understand:

  1. Expressions return value, statements do not.

  2. All expressions are statements, but not otherwise. You cannot use a statement in place of an expression.

In short, expression is value, statement is behavior.

Let me just show you some naive examples.

The following code define a value. It is a statement called let statement led by let keyword. Here 1 is an expression.

// statement
// |---------|
let n = 1 ;
//        |-|
//        expression

And this is for statement led by for keyword. It comes with some nested expressions and statements.

//      expression(1)
//      |-----------|
for (num in numArr) {                 //--+
//  |
sum += (num * 3); // statement(2)  //  |
//            |-----|                    //  |statement(1)
//            expression(2)              //  |
//  |
}                                     //--+

So a statement is an instruction unit telling computer what to DO. for statement, while statement, if statement, they are all actions, in another word tasks, or behaviors.

But for expression, we are talking about values, valuables, objects, or some procedures that can produce a value, like function.

1 + 2
(2 + 3) * 5 === 25
new Foo()

So Javascript also has function expression. Because function is a value. In the following code,

  1. The entire snippet is a statement.
  2. Everything after = is an expression.
  3. return width * height; is nested statement.
  4. width * height is an expression.
const rectArea = function(width, height) {
return width * height;
};