If/Else Statements
Conditionals in EJS work exactly like JavaScript. No new syntax to learnβjust plain if/else blocks wrapped in EJS tags.
<% if (user.isLoggedIn) { %>
Welcome back, <%= user.name %>!
<% } else { %>
Please log in.
<% } %>
The logic is clear and readable. Your HTML structure stays intact around the conditional blocks.
Else If Chains
Need multiple conditions? Chain them with else if:
<% if (score >= 90) { %>
Grade: A
<% } else if (score >= 80) { %>
Grade: B
<% } else if (score >= 70) { %>
Grade: C
<% } else { %>
Grade: F
<% } %>
Works just like you'd expect. The conditions are evaluated in order.
Try it Yourself βTernary Operator
For simple conditionals, the ternary operator keeps things concise:
<%= user.isAdmin ? 'Admin Dashboard' : 'User Dashboard' %>
Short, sweet, and perfect for inline conditions where a full if block would be overkill.
Logical AND Shorthand
Want to show something only if a condition is true? Use &&:
<% if (user.isPremium) { %>
Premium Member
<% } %>
Or even shorter with && for output:
Discount: <%= isPremium && '20% off' %>
The && operator returns the second value if the first is truthy. Neat trick for quick conditional output.