Expressions

in JavaScript

This is an entry in Marek's JavaScript Compendium. Last updated 2020-01-23.

An expression is a piece of code that produces a value when it gets evaluated by the JavaScript engine.

The action of evaluating an expression is called evaluation.

When the JavaScript engine is running a program, it spends most of its time evaluating expressions.

You can think of all the other parts of code (such as control flow statements like if branches and for loops) as directions that indicate which expression (or which groups of expressions) to evaluate next.

Nesting Expressions

Expressions can be nested within other expressions, and they can be nested within statements.

Because expressions can be nested, it's possible to draw a picture of nested expressions as a tree graph. In fact, inside of the JavaScript engine, expressions are understood as a tree data structure.

JavaScript in the real world

Top-level expressions are expressions which are not nested inside of another expression or a statement.

The majority of top-level expressions that you see in real code are of two types: assignment expressions and function call expressions.

What sources say

An expression is a piece of code that can be evaluated to produce a value.
An expression is any valid unit of code that resolves to a value.
Source: MDN

MDN says that an expression "resolves to a value", but I think it's clearer to say that an expression "produces a value when evaluated".

An expression can be evaluated any number of times, and it can produce a different value each time.

It's also possible for an expression in the code to never be evaluated, if the JavaScript engine never reaches it.

See Also