Immediately Invoked Function Expression
IIFE (Immediately Invoked Function Expression) in JSX
An IIFE is a function that is defined and called in the same expression: (() => { ... })(). Inside JSX curly braces, you can place an IIFE to execute a block of code (including if/else or switch) and return JSX from it, all inline, without defining a separate function.
IIFEs in JSX are an advanced pattern used when you need complex logic inline but don’t want to define a separate helper function. It is relatively rare in modern React usually it is cleaner to extract logic into a helper or move the condition before the return.
function GradeCard({ score }) { return ( <div> <h3>Score: {score}</h3> {/* IIFE — run a full if/else block inline in JSX */} {(() => { if (score >= 90) return <span style={{color:'green'}}>Grade: A ⭐</span>; if (score >= 80) return <span style={{color:'blue'}}>Grade: B 👍</span>; if (score >= 70) return <span style={{color:'orange'}}>Grade: C 😊</span>; if (score >= 60) return <span style={{color:'#B45309'}}>Grade: D 😐</span>; return <span style={{color:'red'}}>Grade: F 😢</span>; })()} </div> ); } // Equivalent — cleaner with a helper function (preferred) function getGrade(score) { if (score >= 90) return 'A ⭐'; if (score >= 80) return 'B 👍'; if (score >= 70) return 'C 😊'; if (score >= 60) return 'D 😐'; return 'F 😢'; }
