Expressions in JavaScript
Explore how JavaScript expressions function within JSX to build dynamic React components. Understand valid expressions such as calculations, ternary operators, and array mapping. This lesson helps you grasp embedding code snippets that return values, crucial for enhancing React UI rendering.
We'll cover the following...
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:
- Following one-liner is an expression whose value is
6:
1 + 5;
- This is another example of an expression that concatenates the two strings
Helandlointo a single value,Hello:
'Hel' + 'lo';
- 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
- 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}`;
- 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:
Every JavaScript interpreter would rightly complain because of invalid syntax.
If we omit the if in this snippet, we are left with a Logical AND operator (&&), which is an expression and returns a value. In this case true or false depending on the Boolean condition of active and value of visibility:
Valid expressions
Let’s look at a few other examples of JSX that contain valid JavaScript expressions to solidify these concepts.
- Simple mathematics:
<span>5 + 1 = {5 + 1}</span>
- Ternary operator:
<span>Today is {new Date().getDay() === 1 ? 'Monday' : 'not Monday'}</span>
- Ternary operator as a value of a prop:
<div className={user.isAdmin ? 'is-admin' : null}>…</div>
- Array.map() with JSX as its return value (which in turn contains an expression):
<ul>
{['Tintin', 'Milou'].map((name) => (
<li>{name}</li>
))}
</ul>
- Number values in props:
<input type="range" min={0} max={100} />
All of these are great examples of using expressions to ensure JSX is much more than just HTML.