Node & Express: EJS if/else & if/else if/else conditionals

avatar
Borislav Hadzhiev

Last updated: Apr 5, 2024
5 min

banner

# Table of Contents

  1. Node & Express: EJS If-Else conditional statements
  2. Using an if statement in an EJS template
  3. Using the ternary operator in an EJS template
  4. Using a switch statement in an EJS template
  5. Using if/else if/else conditional statements in EJS

# Node & Express: EJS If-Else conditional statements

To be able to use EJS if-else conditional statements in a Node.js & Express application, first make sure you have ejs and express installed.

shell
# Initialize package.json file npm init -y # Install ejs and express using NPM npm install ejs express # Or using YARN yarn add ejs express

install ejs module

The folder structure for the example is the following.

shell
my-project/ └── index.js └── views/ └── home.ejs
The code for this article is available on GitHub

Here is the code for the index.js file.

index.js
// Using ES6 modules import/export syntax import express from 'express'; import path from 'path'; import {fileURLToPath} from 'url'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const app = express(); app.use( '/static', express.static(path.join(__dirname, 'public')), ); app.set('view engine', 'ejs'); app.get('/', (req, res) => { res.render('home', { title: 'bobbyhadz.com', message: 'Example message: bobbyhadz.com', salary: 500, }); }); const port = 5000; app.listen(port, () => { console.log(`Example app listening on port ${port}`); });
The code for this article is available on GitHub

Make sure to set the type property to module in your package.json file if you want to use the ES6 modules import/export syntax.

package.json
{ "type": "module", "scripts": {}, "dependencies": {}, // ... }

If you want to use the CommonJS require() syntax, use the following code sample instead.

index.js
// 👇️ Using CommonJS require() syntax const express = require('express'); const path = require('path'); const app = express(); app.use( '/static', express.static(path.join(__dirname, 'public')), ); app.set('view engine', 'ejs'); app.get('/', (req, res) => { res.render('home', { title: 'bobbyhadz.com', message: 'Example message: bobbyhadz.com', salary: 500, }); }); const port = 5000; app.listen(port, () => { console.log(`Example app listening on port ${port}`); });

Make sure the type attribute is not set to module in your package.json file if you want to use the CommonJS require() syntax.

And here is the if/else statement in the home.ejs file.

views/home.ejs
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>bobbyhadz.com</title> </head> <body> <h2>bobbyhadz.com</h2> <h2><%= message %></h2> <% if(salary > 0){ %> <h1>Your salary is <%= salary %></h1> <% } else{ %> <h1>Invalid salary supplied. Must be greater than 0.</h1> <% } %> </body> </html>
The code for this article is available on GitHub

I can start a development server with npx nodemon index.js to view the output at http://localhost:5000.

shell
npx nodemon index.js

view result of conditional in browser

Let's go over the if/else statement.

views/home.ejs
<% if(salary > 0){ %> <h1>Your salary is <%= salary %></h1> <% } else{ %> <h1>Invalid salary supplied. Must be greater than 0.</h1> <% } %>

The first line checks if the salary variable is greater than 0.

We passed the salary variable to the home.ejs view in the route handler and set it to 500.

index.js
app.get('/', (req, res) => { res.render('home', { title: 'bobbyhadz.com', message: 'Example message: bobbyhadz.com', salary: 500, }); });

The next line is the output that is shown if the if condition is met.

views/home.ejs
<% if(salary > 0){ %> <h1>Your salary is <%= salary %></h1> <% } else{ %> <h1>Invalid salary supplied. Must be greater than 0.</h1> <% } %>

Then we have an else statement.

The else block runs if the if condition isn't met, in which case the second h1 element is shown.

In order to test this, I'll set the salary variable to -100.

index.js
app.get('/', (req, res) => { res.render('home', { title: 'bobbyhadz.com', message: 'Example message: bobbyhadz.com', salary: -100, }); });

If I refresh the page, I can see that the else block in the EJS template is run.

else block runs

You can also use other logic and expressions in your conditional EJS statements.

index.js
<% if(new Date().getFullYear() > 2020){ %> <h1>The year is greater than 2020</h1> <% } else{ %> <h1>The year is NOT greater than 2020</h1> <% } %>
The code for this article is available on GitHub

We used the Date.getFullYear method to get the current year and compared it to the year 2020.

If I load the code in my browser, I can see that the if block runs.

if block runs condition is met

# Using an if statement in an EJS template

If you only want to use an if statement in your EJS template, use the following syntax.

views/home.ejs
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>bobbyhadz.com</title> </head> <body> <h2>bobbyhadz.com</h2> <h2><%= message %></h2> <% if(salary > 0){ %> <h1>Your salary is <%= salary %></h1> <% } %> </body> </html>
The code for this article is available on GitHub

The if statement checks if the salary variable is greater than 0 and prints a message if the condition is met.

# Using the ternary operator in an EJS template

You can also use the ternary operator to simulate an if/else statement in an EJS template.

The ternary operator in the example:

  1. Checks if the salary variable is greater than 0.
  2. If the condition is met, the string GT 0 is returned.
  3. If the condition isn't met, the string LT or Equal to 0 is returned.
views/home.ejs
<h2><%- salary > 0 ? 'GT 0' : 'LT or Equal to 0' %></h2>

Here is a nested ternary that is a bit more complex.

views/home.ejs
<h2> <%- salary > 0 ? 'GT 0' : salary < 0 ? 'LT 0' : salary %> </h2>

The ternary operator:

  1. Checks if the salary variable is greater than 0.
  • If the condition is met, the string GT 0 is returned.
  • If the condition isn't met, another ternary operator is returned.
  1. The second ternary operator checks if the salary variable is less than 0.
  • If the condition is met, the string LT 0 is returned.
  • Otherwise, the value of the salary variable is returned.

# Using a switch statement in an EJS template

You can also use a switch statement in your EJS templates.

views/home.ejs
<% switch (title) { case 'bobbyhadz.com' : %> Site is bobbyhadz.com <% break; case 'example.com' : %> Site is example.com <% break; case 'google.com' : %> Site is google.com <% break; } %>
The code for this article is available on GitHub

We passed the value of the title variable to the switch() statement.

index.js
app.get('/', (req, res) => { res.render('home', { title: 'bobbyhadz.com', message: 'Example message: bobbyhadz.com', salary: 500, }); });

The first case clause checks if the value of the title variable is equal to bobbyhadz.com and is matched, so the corresponding string is returned and rendered.

# Using if/else if/else conditional statements in EJS

You can also use if/else if/else conditional statements in your EJS templates.

views/home.ejs
<% if (salary > 0) { %> <h2>The salary variable is greater than 0</h2> <% } else if (salary < 0) { %> <h2>The salary variable is less than 0</h2> <% } else { %> <h2>The salary variable is equal to 0</h2> <% } %>
The code for this article is available on GitHub

The if statement checks if the salary variable is greater than 0.

If the condition is met, the corresponding h2 tag is returned.

The else if statement checks if the salary variable is less than 0.

If neither condition is met, the else block runs which means that the salary variable is equal to 0.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.