Code Synopsis logo

What are JavaScript Statements vs Expressions?

Let’s start with the statement.

JavaScript code is a set of instructions called statements. You might think of a statement as saying, ”Do this action.”

The following statement tells JavaScript to replace the HTML content inside a certain page element:

document.getElementById("example").innerHTML = "Some new text.";

Think of a JavaScript statement as a complete idea or a sentence, and they should be terminated with a semicolon. JavaScript will usually understand statements that are on separate lines without semicolons, but with missing semicolons, if the code is ever minimized then errors could be introduced. For this reason, I recommend adopting the habit of ending statements with a semicolon.

JavaScript statements often begin with a keyword , a word that has special meaning in JavaScript. Keywords are also known as reserved words because they cannot be used as identifiers (a.k.a., the name of a function, variable, or label).

A variable declaration statement uses the var, let, or const keyword like this:

var a = 2;

Other commonly used statement keywords include for loops and if statements. See the MDN docs for details.

So what about expressions?

An expression is like a phrase describing a computation. They are used where JavaScript would expect a value. An expression followed by a semicolon is considered an expression statement.

Below is a JavaScript statement that contains the expression a + 4:

var b = a + 4;

In the next example, line 1 is a statement. Line 2 is a function declaration statement. The function invocation on line 3 is an expression statement. Expressions can be used as arguments in a function because they evaluate to a value. Here, the expression argument a + 4 is evaluated and passes in 6, which is then doubled.

var a = 2; function doubleIt(x) { return x * 2; }; doubleIt(a + 4); // 12

When an expression creates a new object, it is called an object literal:

{ name: 'Sam', age: '68' }

Here it is in a statement:

let person = { name: 'Sam', age: '68' };

Related posts:

Helpful references:

Have feedback on this topic?