How to check for undefined property in EJS for Express JS ?
Last Updated :
13 Mar, 2024
This article explores various techniques to handle undefined properties within EJS templates used in ExpressJS applications. It guides you on how to gracefully manage scenarios where data passed to the template might lack specific properties, preventing errors and ensuring a smooth user experience.
We will discuss different types of approaches to check for undefined properties in EJS for ExpressJS.
Using Conditional Statements (if-else):
We can directly use an if statement to check if a variable exists before attempting to access its properties.
- With this approach, we can use traditional if-else statements to check if a property is undefined and then render content based on the condition.
- This method provides flexibility in handling different scenarios by allowing us to specify distinct actions for when a property is defined and when it's undefined
<% if (user.name !== undefined) { %>
<h1>Welcome, <%= user.name %>!</h1>
<% } else { %>
<h1>Welcome, Guest!</h1>
<% } %>
Using Ternary Operators:
The ternary operator provides a concise way to conditionally render content based on the existence of a property.
- Ternary operators offer a concise way to handle undefined properties by providing a conditional expression.
- This approach is particularly useful for simpler conditions and scenarios where you want to keep your code compact.
<h1>Welcome, <%= user.name !== undefined ? user.name : 'Guest' %>!</h1>
Implementing Default Values with the || Operator:
The typeof operator can be employed to check the type of a variable and handle undefined properties accordingly.
- The || (OR) operator allows us to set default values for undefined properties, ensuring a fallback option.
- This approach is straightforward and efficient, providing a clean way to handle missing data.
<h1>Welcome, <%= user.name || 'Guest' %>!</h1>
Using the typeof Operator:
We can use the || (OR) operator to provide a default value in case a property is undefined.
- By using the typeof operator, we can check the type of a variable and handle undefined properties accordingly.
- This approach is particularly useful when we need to handle different data types or perform additional checks based on property existence.
<% if (typeof user.age !== 'undefined') { %>
<p>Your age: <%= user.age %></p>
<% } else { %>
<p>Your age: Not specified</p>
<% } %>
Note:- Each of these approaches offers its own advantages and is suitable for different use cases. It's essential to choose the approach that best fits your requirements in terms of readability, maintainability, and performance.
Steps to Create Express JS App & Installing Module:
Step 1: Create a new directory for your project:
mkdir ejs-undefined-properties
Step 2: Navigate into the project directory:
cd ejs-undefined-properties
Step 3: Initialize npm (Node Package Manager) to create a package.json file:
npm init -y
Step 4: Install required modules (Express and EJS) using npm:
npm install express ejs
Project Structure:

The updated dependencies in package.json file will look like:
"dependencies": {
"ejs": "^3.1.9",
"express": "^4.18.2"
}
Example: Below is an example of hacking undefined property in EJS for nodeJS.
- Case 1: When both user.name and user.age are defined:
Welcome, GFG!
Your age: 30
- Case 2: When user.name is undefined but user.age is defined:
Welcome, GuestGFG!
Your age: 30
- Case 3: When both user.name and user.age are undefined:
Welcome, Guest!
Your age: Not specified
HTML
<!-- views/index.ejs -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Handling Undefined Properties</title>
</head>
<body>
<h1>Welcome, <%= user.name || 'Guest' %>!</h1>
<p>Your age: <%= user.age ? user.age : 'Not specified' %>
</p>
</body>
</html>
JavaScript
const express = require('express');
const app = express();
const port = 3000;
app.set('view engine', 'ejs');
app.get('/', (req, res) => {
const user = { name: 'GFG'};
res.render('index', { user });
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Output:
Output:- when age is undefined
Similar Reads
How to check for undefined property in EJS for Node.js ?
Handling undefined attributes is essential when working with EJS templates in a NodeJS application to guarantee a seamless and error-free user experience. In this post, we'll examine one of the most basic methods for determining whether a variable is defined or not, which involves utilizing a simple
3 min read
How to check for "undefined" value in JavaScript ?
In JavaScript, undefined is a primitive value that represents the absence of a value or the uninitialized state of a variable. It's typically used to denote the absence of a meaningful value, such as when a variable has been declared but not assigned a value. It can also indicate the absence of a re
3 min read
How to Resolve form-data is getting undefined in Node/Express API ?
Working with forms and handling data submissions is a basic requirement in web development. When using Node and Express for building APIs, you might get an error that the FormData object is undefined. In this article, we'll explore how to resolve form data getting undefined in a Node/Express API. Th
3 min read
How to render JSON in EJS using Express.js ?
EJS (Embedded JavaScript) is a templating language that allows dynamic content generation in NodeJS applications. It allows us to embed JavaScript code directly into Our HTML code, and with the help of that we can generate the dynamic content on the server side. So with the help of ejs, we can perfo
4 min read
How to Detect an Undefined Object Property in JavaScript ?
Detecting an undefined object property is the process of determining whether an object contains a certain property, and if it does, whether the value of that property is undefined. This is an important concept in JavaScript programming, as it helps to prevent errors that can occur when attempting to
3 min read
How to use Template Engines in Express JS ?
Express.js is a popular web framework for Node.js that simplifies the process of building web applications. One of the key features of Express is its ability to integrate with template engines, allowing developers to dynamically generate HTML pages with data from their server. In this article, we'll
2 min read
How to check empty/undefined/null string in JavaScript?
Empty strings contain no characters, while null strings have no value assigned. Checking for an empty, undefined, or null string in JavaScript involves verifying if the string is falsy or has a length of zero. Here are different approaches to check a string is empty or not. 1. Using === OperatorUsin
2 min read
How to use get parameter in Express.js ?
Express Js is a web application framework on top of Node.js web server functionality that reduces the complexity of creating a web server. Express provides routing services i.e., how an application endpoint responds based on the requested route and the HTTP request method (GET, POST, PUT, DELETE, UP
2 min read
How to set Error.code property in Node.js v12.x ?
Setting setError.code property in Node.js v12.x or above is a bit complex process, but In this article, you will learn to do this in a very easy way. Problem Statement: Sometimes we want to set the error code manually, we want to show our own error code instead of a pre-built error code when throwin
2 min read
How to Configure multiple View Engines in Express.js ?
View engines present in web application framework are basically the template engines that allow us to embed dynamic content into the web pages, render them on the server, and send them to the client. With the help of these, we can serve dynamic data, and utilise the template inheritance properties t
3 min read