For Loops
Loops in EJS work just like JavaScript loops. Wrap them in EJS tags and you're good to go.
<% for (let i = 0; i < items.length; i++) { %>
<%= items[i] %>
<% } %>
Standard for loop. Simple, familiar, gets the job done.
ForEach Loops
For arrays, forEach is often cleaner:
<% fruits.forEach(function(fruit) { %>
<%= fruit %>
<% }); %>
Each iteration gives you the current item. Perfect for rendering lists.
Try it Yourself →While Loops
While loops work too, though they're less common in templates:
<% let count = 0; %>
<% while (count < 5) { %>
Count: <%= count %>
<% count++; %>
<% } %>
Useful when you need a loop with a condition rather than a fixed range.
Loop Variables
EJS gives you helpful loop variables like loop.index, loop.first, and loop.last when using forEach:
<% items.forEach(function(item, loop) { %>
<%= loop.index + 1 %>. <%= item %>
<%= loop.last ? ' (Last one!)' : '' %>
<% }); %>
These variables make it easy to style items differently based on their position.
Iterating Objects
Need to loop through an object's properties? Use Object.keys:
<% Object.keys(settings).forEach(function(key) { %>
<%= key %>: <%= settings[key] %>
<% }); %>
This gives you both the key and value for each property. Great for rendering configuration or metadata.