Javascript: difference between a statement and an expression?
JavascriptExpressionTerminologySemanticsJavascript Problem Overview
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 string of code that could be used for _X_
in the following snippet also be used for _Y_
and vice versa? if(_X_) _Y_
Javascript Solutions
Solution 1 - Javascript
> 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.
Solution 2 - Javascript
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.
Solution 3 - Javascript
At its simplest terms, expressions are evaluated to produce a value. On the other hand, statements are executed to make something happen.
Solution 4 - Javascript
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];
Solution 5 - Javascript
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 () {}
Solution 6 - Javascript
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
Solution 7 - Javascript
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.
If the browser returns any value other than undefined
after each line of execution, its an expression.
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:
-
Expressions
return
value, statements do not. -
All expressions are statements, but not otherwise. You cannot use a statement in place of an expression.
Solution 8 - Javascript
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 E
qual 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.
E
very E
xpression can be used as a statement
(whose effect is to evaluate the expression, and ignore the resulting value).
But an E
xpression is any section of the code that e
valuates 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.
> 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):
Solution 9 - Javascript
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,
- The entire snippet is a statement.
- Everything after
=
is an expression. return width * height;
is nested statement.width * height
is an expression.
const rectArea = function(width, height) {
return width * height;
};
Solution 10 - Javascript
We have the following two types of expressions:
1. Boolean expression is uses to execute block of statements.
2. Arithmetic expression is uses for variable assignments, which acts as a statements too.
For example: number = number + 1;
Solution 11 - Javascript
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.