UNB/ CS/ David Bremner/ teaching/ cs2613/ books/ mdn/ Reference/ Statements and declarations

JavaScript applications consist of statements with an appropriate syntax. A single statement may span multiple lines. Multiple statements may occur on a single line if each statement is separated by a semicolon. This isn't a keyword, but a group of keywords.

Statements and declarations by category

For an alphabetical listing see the sidebar on the left.

Control flow

Declaring variables

Functions and classes

Iterations

Others

Difference between statements and declarations

In this section, we will be mixing two kinds of constructs: statements and declarations. They are two disjoint sets of grammars. The following are declarations:

Everything else in the list above is a statement.

The terms "statement" and "declaration" have a precise meaning in the formal syntax of JavaScript that affects where they may be placed in code. For example, in most control-flow structures, the body only accepts statements — such as the two arms of an if...else:

if (condition)
  statement1;
else
  statement2;

If you use a declaration instead of a statement, it would be a SyntaxError. For example, a let declaration is not a statement, so you can't use it in its bare form as the body of an if statement.

if (condition)
  let i = 0; // SyntaxError: Lexical declaration cannot appear in a single-statement context

On the other hand, var is a statement, so you can use it on its own as the if body.

if (condition)
  var i = 0;

You can see declarations as " identifiers to values", and statements as "carrying out actions". The fact that var is a statement instead of a declaration is a special case, because it doesn't follow normal lexical scoping rules and may create side effects — in the form of creating global variables, mutating existing var-defined variables, and defining variables that are visible outside of its block (because var-defined variables aren't block-scoped).

As another example, labels can only be attached to statements.

label: const a = 1; // SyntaxError: Lexical declaration cannot appear in a single-statement context

Note: there's a legacy grammar that allows function declarations to have labels, but it's only standardized for compatibility with web reality.

To get around this, you can wrap the declaration in braces — this makes it part of a block statement.

label: {
  const a = 1;
}

if (condition) {
  let i = 0;
}

Browser compatibility

See also