Statements vs Expressions in JavaScript

Expressions

An expression evaluates into (results in) a single value.

For example, these are all expressions:

  • 1 → produces 1
  • "hello" → produces "hello"
  • 5 * 10 → produces 50
  • num > 100 → produces either true or false
  • [1, 2, 3].pop() → produces the number 3

Broadly speaking there are two types of expressions -

An expression that is already a single value

When you first declare a variable using the let keyword, it is given a special value of undefined.

In order for a variable to be useful, it needs to be given a value. This is done using the assignment operator (the equals sign).

let color;
color = "red";

Here the value red is an expression.

An expression that uses two or more values to return a single value

You can perform operations on any number of individual values to determine a single value.

For example:

let area = 3 * 2;

Here the expression 3 * 2 evaluates into 6.

Another example where an expression uses two values to yield a single value would be where two strings are joined to create a single string.

Statements

A JavaScript program is a sequence of statements. Each statement is an instruction for the computer to do something.

Here are some examples of statements in JavaScript:

let hi = 5;
if (hi > 10) {
  // More statements here
}
throw new Error("Something exploded!");

Statements often have "slots" for expressions. We can put any expression we like into those slots.

For example, declaring a variable has an expression slot:

let hi = /* some expression */;

A handy trick

Want to know whether a chunk of JS is an expression or a statement? Try to log it out!

console.log(/* Some chunk of JS here */);

If it runs, the code is an expression. If you get an error, it's a statement (or, possibly, invalid JS).

In summary

A JavaScript program consists of a sequence of statements. Each statement is an instruction to do something, like create a variable, run an if/else condition, or start a loop.

Expressions produce a value, and these values are slotted into statements. Expressions are always part of a statement.

It can take a while for this distinction to become intuitive, but hopefully, this article post has clarified a few things!

Get my free, weekly JavaScript tutorials

Want to improve your JavaScript fluency?

Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.

Join today, and level up your JavaScript every Sunday!

Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.

- Remi Egwuda