Expressions in JavaScript

Learn about the power of JavaScript expressions in JSX, as well as the difference between valid and invalid expressions.

What is an expression in JavaScript?

What exactly does it mean for us to be able to use JavaScript expressions in JSX?

A JavaScript expression is not much more than a piece of code that will generate a value or return a result after its operation. Simply put, anything that you can write on the right side of a variable declaration ( after the = sign) is a JavaScript expression. Let’s look at some examples:

  1. Following one-liner is an expression whose value is 6:
1 + 5;
  1. This is another example of an expression that concatenates the two strings Hel and lo into a single value, Hello:
'Hel' + 'lo';
  1. We could use any of the following as an expression since all JavaScript data types can be used as an expression:
6
'Hello'
[1,2,3,4]
{a: 1, b: 2, c: 3}
true
null
  1. The ES2015 Template String Syntax is another expression. Even though we are using backticks (``), they are just a plain string in the end:
`Hello ${name}`;
  1. The ternary operator ( ?: ) is also an expression:
Condition ? true : false;

Expressions are not limited to Boolean values, numbers, or strings but can also include objects, arrays, or even functions and arrow function calls.

Example for an arrow function:

(number) => {
  return number * 2;
};

All of this is important. Expressions can, in turn, include other JSX. You could make an endless series of expressions if you want.

Invalid expression

However, this is not an expression:

if (active && visibility === 'visible') { … }

This is because we cannot simply write code like this:

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy