Expressions

Learn what expressions are and how JavaScript evaluates them to produce values.

May 1, 20262 min read3 / 3

The Essentials

  1. Expressions vs Values: An expression is not a value itself; rather, it is a snippet of code that evaluates (or resolves) to a value.
  2. Everywhere a Value Goes: Anywhere JavaScript expects a value, you can pass an expression instead. The language will evaluate the expression first and then use the resulting value.
  3. Compound Expressions: You can combine multiple operators and values into complex expressions (like 4 / 2 * 10), and JavaScript will resolve the entire thing down to a single value.

In previous posts, I looked at values (like 42 or "ALOHA") and operators (like + or ===). Now it is time to put them together.

When you write a snippet of JavaScript code like 4 / 2 * 10 or "Front" + "end", you are writing an expression.

Are these snippets values? Sort of, but not exactly. In technical terms, an expression is a unit of code that evaluates to a value. You might also hear developers say that an expression resolves to a value.

You can think of it like natural language. In American English, there is a common phrase: "a New York minute". Because everyone in New York walks so fast and is always in a hurry, this three-word expression actually means "an instant". The phrase itself is not the instant, but it resolves to the concept of an instant in the listener's mind.

JavaScript works the same way. When the engine encounters "Front" + "end", it does not see a value. It sees an expression that it must evaluate. Once it evaluates it, it gets the value "Frontend".

Using Expressions

The most powerful thing about expressions is this golden rule: anywhere JavaScript expects a value, you can give it an expression instead.

For example, if you want to ask if a string includes a specific word, you would normally pass a string value into the .includes() method:

JavaScript
"FrontendMasters".includes("Frontend") // Returns true

But because of the golden rule, I do not have to pass a hardcoded value. I can pass an expression.

JavaScript
"FrontendMasters".includes("Front" + "end") // Returns true

When JavaScript runs this code, it pauses for a moment. It looks inside the parentheses and sees an expression. Before it can run the .includes() method, it evaluates "Front" + "end" down to the single string value "Frontend". Then, it hands that value to .includes().

This is the secret to building dynamic programs. You rarely know the exact values you will be working with ahead of time (they depend on user input, API data, or database queries). But because you can use expressions anywhere a value is expected, you can write flexible code that calculates what it needs on the fly.

Further Reading