Loading lessons...
Embedding JavaScript Expressions
Embedding JavaScript Expressions in JSX
One of React's greatest strengths is allowing you to seamlessly embed any valid JavaScript expression directly inside your markup using curly braces { }.
Using Curly Braces { }
Any valid JavaScript variable, function call, math operation, or logical expression can be placed between curly braces { } within JSX text or attribute values.
function UserGreeting() {
const name = "Sarah";
const userScore = 95;
function getBadge(score) {
return score >= 90 ? "Gold" : "Silver";
}
return (
<div>
<h2>Hello, {name.toUpperCase()}!</h2>
<p>Score: {userScore + 5}</p>
<p>Badge: {getBadge(userScore)}</p>
</div>
);
}
What Values Render vs What Gets Ignored
React renders strings, numbers, and arrays directly. However, booleans, null, and undefined are ignored and render nothing.
| Data Type | JSX Output (<div>{val}</div>) |
|---|---|
String ("Hello") | Rendered as text: Hello |
Number (42) | Rendered as text: 42 |
Boolean (true / false) | Nothing rendered (empty) |
null / undefined | Nothing rendered (empty) |
Array (['A', 'B']) | Concatenated rendering: AB |
Object ({ a: 1 }) | ❌ Error: Objects are not valid as JSX children |
// ❌ WRONG: Passing plain object directly causes runtime error
const user = { name: "Alex" };
return <div>{user}</div>; // Error!
// ✅ CORRECT: Accessing specific object properties
return <div>{user.name}</div>;
Summary & TL;DR
- Wrap any valid JavaScript expression in curly braces
{ }inside JSX. - Functions, variable references, arithmetic, and ternary expressions can all be evaluated inside
{ }. - Booleans (
true/false),null, andundefinedare ignored by React when rendered inside JSX. - Plain JavaScript objects cannot be rendered directly as children.