3.2.1: EJS Loops


We can perform JS loops in EJS, for example to create an HTML element for each element in an array.



app.get('/bananas', (request, response) => {
// data contains an array of elements, each representing 1 user
const data = {
users: [{ name: 'kai' }, { name: 'jim' }, { name: 'susan' }],
response.render('index', data);


  1. 1.
    Loops run inside EJS tags, and we wrap each conceptual line of JS in its own EJS tags. Notice how the opening and closing lines of the loop are inside separate EJS tags <% %>.
  2. 2.
    The <li> is outside EJS tags. The variable is in a tag that uses the <%= %> tag, where the = denotes variable substitution instead of JS code execution.
<!-- Create an <li> element for each user in users -->
<% users.forEach((user) => { %>
<li><%= %></li>
<% }); %>

Further Reading

Read more about the various EJS tags in the Tags section on the EJS website.