Immediately Invoked Function Expressions (IIFEs) in JSX
What you'll learn: How to embed multi-statement logic directly inside JSX when simple ternaries and && operators aren't enough.
The Problem with Complex Logic in JSX
You've learned that JSX curly braces {} accept expressions, not statements. This means you can't write if/else blocks, switch cases, or multiple lines of logic directly in your JSX. Sometimes extracting everything to variables feels cumbersome, especially for small bits of complex conditional rendering.
IIFEs: The Inline Function Workaround
An Immediately Invoked Function Expression lets you wrap statements inside a function, then call it immediately. Since the function call is an expression, it works perfectly in JSX:
return (
<div>
{(() => {
if (score >= 90) return <span>A</span>;
if (score >= 80) return <span>B</span>;
return <span>C</span>;
})()}
</div>
);
Notice the pattern: (() => { /* statements */ })() — you define an arrow function and immediately invoke it with the trailing ().
When to Use IIFEs
Perfect for:
- Switch statements that pick between many components
- Multi-step logic where you need intermediate calculations
- Complex conditions where nested ternaries become unreadable
The Readability Trade-off
IIFEs keep logic close to where it's used, but they add visual noise. If your IIFE grows beyond 5-6 lines, extract it to a variable or helper function before the return statement instead.
Key Takeaway: IIFEs let you embed imperative logic (if/else, switch, loops) directly in JSX by wrapping statements in an immediately-called function — use them sparingly when simpler approaches don't fit.