Nearby lessons

9 of 14

Logics and Loops Using EJS in Express JS | forEach, for, while, if-else

What is EJS Logic?

Using JavaScript Logic Inside EJS Templates

EJS allows us to write JavaScript code directly inside HTML using special tags. This makes it easy to iterate arrays, run loops, and apply conditions while rendering dynamic views.

In this tutorial, you will learn how to use forEach, for loop, while loop, and if-else statements inside EJS templates.

Step 1: Iterate Array Data Using forEach

This example shows how to send an object from Express to EJS and iterate over an array using forEach().

 project-folder
  views
   home.ejs
  index.js
        
Express.js Server
NODE RUNTIME
const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors());
app.set('view engine', 'ejs');

app.get('/', (req, res) => {
    let Employee = {
        name: 'Codings',
        surname: 'Points',
        year: 2025,
        hobbies: ['Reading', 'Dancing', 'Watching', 'Sleeping']
    }
    res.render('home', { emp: Employee });
});

app.listen(8080, () => {
    console.log("Server running at http://localhost:8080");
});

Browser Output
Server logs

πŸ” Step 2: Using for Loop, while Loop & if else in EJS

EJS allows us to use all JavaScript logical structures. Below is an example demonstrating for loop, while loop, and if-else inside EJS.

Express.js Server
NODE RUNTIME
var express = require('express');
var app = express();

app.set('view engine', 'ejs');

app.get('/', (req, res) => {
    res.render('home');
});

app.listen(8080, () => {
    console.log("Server running at http://localhost:8080");
});

Browser Output
Server logs

πŸ“˜ How It Works

  • πŸ”— <%= %> is used to output dynamic data inside HTML.
  • 🧠 <% %> is used for running JavaScript logic (loops, conditions, etc.).
  • πŸ” The forEach() method is ideal for iterating arrays passed from Express.
  • βš™οΈ for and while loops work exactly as they do in JavaScript.
  • 🚦 if-else helps in rendering dynamic UI based on conditions.
  • πŸ“„ All these logics run on the server when EJS creates the final HTML page.

🧠 Test Your Knowledge

5 Questions

Progress: 0 / 5
Keep Going!Share Code Across Pages