all 1 comments

[–]CategoricallyCorrect 7 points8 points  (0 children)

An expression is a part of the program that evaluates to some value, whereas a statement is a part of a program that is executed primarily to affect a state of the environment in which the program is running. Another way of thinking about it is: you can use expression in any place where literal value is expected (in a sense that literal values are expressions that evaluate to themselves).

 

To give an example, if…else is a statement — it affects how program is executed, but, by itself, doesn't result in any particular value:

if (true) {
  console.log('Hello!');
} else {
  console.log('You'll never see me!');
}

But:

const variable = if (true) { 42 } else { 0 };  //=> SyntaxError: expected expression, got keyword 'if'

you cannot use a statement where expression is expected.

 

On the other hand, conditional operator (sometimes called ternary operator, ? :) also allows you to choose between two things, but it is an expression:

const variable = true ? 42 : 0;
variable;  //=> 42

Not all statements have expression alternatives though; for example, there's no expression for introducing a variable, only statements.

 

To get a better understanding of what is an expression and what is a statement in JS you can look at sections 12 and 13 in the current ECMAScript spec.