JavaScript: difference between a statement and an expression?
Asked Answered
B

11

102

I asked this question earlier, and after thinking about the topic some more, I began to wonder where the seemingly fuzzy boundary between the meanings of the terms "statement" and "expression" lies. Are all statements also expressions? Where do the return values in a REPL console come from? They don't always seem to make any intuitive sense. Of course, if you type 1+1, you'll get 2, but other times it isn't as obvious what the logic is.

Given that anything typed into REPL produces some value, does it mean that it can be used in JS source code as both an expression and a standalone statement?

Can the string of code that could be used for _X_ in the following snippet also be used for _Y_ and vice versa? if(_X_) _Y_?

Bronchia answered 3/10, 2012 at 6:46 Comment(2)
The fact that you can evaluate JS code makes me think that all statements are expressions in JSSebastiansebastiano
“Where do the return values in a REPL console come from?” — from completion records. Also see Why does this dowhile loop repeat the last value after the end?.Fash
C
68

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.

Compact answered 3/10, 2012 at 6:55 Comment(2)
Some further reading for people interested in finding out more about javascript statement and expression, ie. differences, keywords, and so on : developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/… and also developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Scrogan
You can’t write the valid expression {"x": 2} as a statement unless you wrap it in parentheses.Fash
K
63

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.

Killiecrankie answered 6/4, 2016 at 15:44 Comment(5)
Great answer! ThanksVasques
the depth difference comes from different number of variables. statement style introduces a new variable g in scope, expression style does not. when adding let g= before expression, then the depths will be equalSoricine
@Soricine the execution context is what's holding the local variables. Function expressions do not add anything to the execution context whereas function declarations do. See also: https://mcmap.net/q/24674/-what-is-the-39-execution-context-39-in-javascript-exactlyKilliecrankie
This should be the accepted answer. It actually answers all parts of OP's question, and it does so beautifully.Hermes
statements and declarations are the same?Supplicatory
A
38

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

Almuce answered 13/7, 2016 at 10:14 Comment(5)
A statement can also be evaluated to produce a value, e.g. var x = makeSomethingHappen();, so this answer isn't correct. (Did you read the accepted answer? It's been covered.)Narvik
Correct me if am wrong, but isn't this considered an "expression statement"? I understand that a statement can also be evaluated to produce a value as you demonstrated above. But a difference between an expression and a statement can be summarised as I did above?Almuce
Sure, but this answer still adds nothing that isn't covered in the accepted answer.Narvik
Except that the accepted answer is misleading at best. At least this answer does not mislead.Brescia
@Narvik you are wrong. If you read more carefully about what marcus said "So whether something is an expression or a statement cannot (in the general case) be pronounced 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 pronounced only after the code is (mentally or actually) parsed." then you can realize that var x = makeSomethingHappen(); will not produce any value because var x = whaterver will not return anything, only makeSomethingHappen() will, but again, read the statament from above...Assail
D
21

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];
Diane answered 6/11, 2013 at 10:50 Comment(2)
x=5; is an "expression statement". x=5 (without the semicolon) is an expression. Whether behavior is produced or something is done or not is not the defining criterion - see my answer for more.Killiecrankie
setTimeout() is an expression. It even produces a value. delete a[5] is also an expression. “Expression produces or evaluates some value.” — would you consider new Array(-1), JSON.parse("x"), (function(){"use strict"; x = 2;})() or () => {await 3;} expressions? They all throw errors.Fash
L
15

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 () {}
Leporid answered 14/6, 2017 at 6:56 Comment(0)
K
10

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

Khan answered 22/11, 2016 at 18:11 Comment(1)
Good link Eldiyar.Takeoff
L
10

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.

Lactary answered 6/10, 2020 at 1:36 Comment(4)
"If the browser returns undefined after each line of execution, its a statement" - except expressions which actually return undefined as a resultAerialist
@Aerialist Is that not already mentioned?Lactary
No. You have written: "If the browser returns undefined after each line of execution, it's a statement." Expression may return undefined as a result (e.g. (function(){ return undefined })()), but according to your answer it should be treated as a statement.Aerialist
@Aerialist Thanks for pointing that out. I have updated the answer.Lactary
B
5

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):
Boozy answered 26/12, 2017 at 21:15 Comment(0)
T
2

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;
};
Tinsmith answered 1/2, 2022 at 21:21 Comment(0)
B
0

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;

Balbriggan answered 18/8, 2016 at 4:0 Comment(0)
T
0

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

Trager answered 8/2, 2020 at 13:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.