wwaawaw wwaawaw - 1 month ago 7
Javascript Question

Javascript: difference between a statement and an expression?

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_

Answer

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.

Comments