Expressions vs statements

If you know how to use a programming language to build things, it can be easy to run away with your code without understanding the fundamentals behind why the syntax you used is working (hence why there is a whole book series called You Don’t Know JS). Until you hit an error of course!

Today we were practicing conditional rendering in React and it led us on a back-to-basics discussion about the difference between expressions and statements. I asked myself if I would be able to explain the difference to someone else and I wasn’t completely sure, so I decided to give myself an explicit reminder today.

In JavaScript expressions are any unit of code that can be evaluated to a value, so can appear anywhere where values are expected.

1 + 1; // arithmetic expression
"hello" + "world"; // string expression
1 < 2; // logical expression
"hello world"; // primary expression - a string literal

Statements do not resolve to values, they are instructions to perform actions.

const sum; // declaration statement

function greeting(message) {
  console.log(message);
} // function declaration statement

if (time < 18) {
  greeting("good day");
} else {
  greeting("good evening");
} // conditional statement - executes based on the value of the expression time < 18

In JavaScript you can write an expression where a statement is expected, but not the other way around.

console.log(const a); // trying to pass a statement as a function argument results in an error