How to check for undefined property in EJS for Node.js ?
Last Updated :
23 Jul, 2024
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 if statement.
Approach to check for undefined property in EJS for NodeJS:
Using <% if (variable) { %> Syntax:
The <% if (variable) { %> syntax is a classic way to check for the existence of a variable in an EJS template. This approach is suitable for scenarios where you want to perform a specific action only if the variable is defined.
Steps to Create Node App & Install Required Modules:
Step 1: Firstly, we will make the folder named root by using the below command in the VScode Terminal. After creation use the cd command to navigate to the newly created folder.
mkdir root
cd root
Step 2: Once the folder is been created, we will initialize NPM using the below command, this will give us the package.json file.
npm init -y
Step 3: Once the project is been initialized, we need to install Express and EJS dependencies in our project by using the below installation command of NPM.
npm i express ejs
Project Structure:

The updated depedencies in package.json file will look like:
"dependencies": {
"express": "^4.17.1",
"ejs": "^3.1.6"
}
Example: Let's create a simple NodeJS application with a route rendering an EJS template that utilizes the if statement to check for undefined properties.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>EJS If Statement Example</title>
</head>
<body>
<h1>EJS If Statement Example</h1>
<% if (user && user.username) { %>
<h2>Hello, <%= user.username %>!</h2>
<% } else { %>
<p>Welcome, guest!</p>
<% } %>
</body>
</html>
JavaScript
const express = require('express');
const app = express();
const port = 4000;
// Set EJS as the view engine
app.set('view engine', 'ejs');
// Define a route
app.get('/', (req, res) => {
// Simulate a user object with username
const user = { username: 'GeeksforGeeks' };
res.render('index', { user });
});
// Start the server
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
Start your server using the following command.
node app.js
Output:Visit http://localhost:3000 in your browser to see the example in action.
Conclusion:
Using a simple if statement in EJS templates provides a clear and concise way to check for undefined properties. This approach is effective for straightforward scenarios where you want to conditionally render content based on the existence of a variable. In the next parts of this series, we'll explore additional approaches to handling undefined properties in more complex situations. Remember, choosing the right approach depends on the specific requirements of your application. Stay tuned for more insights into handling undefined properties in EJS for Node.js.
Similar Reads
How to check for undefined property in EJS for Express JS ? 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.
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
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 throwing
2 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 check null and undefined in TypeScript ? In this article let's learn how to check if a variable is null or undefined in TypeScript. A variable is undefined when it's not assigned any value after being declared. Null refers to a value that is either empty or doesn't exist. null means no value. To make a variable null we must assign null val
3 min read
How Should Unhandled Errors Preferably be Resolved in Node.js ? Unhandled errors in Node.js can lead to unexpected application crashes, data corruption, and poor user experiences. Effectively managing these errors is crucial for building robust and reliable applications. In this article, we'll explore best practices for handling unhandled errors in Node.js, ensu
5 min read
How to handle an undefined key in JavaScript ? In this article, we will try to analyze how we may handle an undefined key (or a property of an object) in JavaScript using certain techniques or approaches (via some coding examples). Firstly let us quickly analyze how we may create an object with certain keys along with their values using the foll
3 min read
How to check for null values in JavaScript ? The null values show the non-appearance of any object value. It is usually set on purpose to indicate that a variable has been declared but not yet assigned any value. This contrasts null from the similar primitive value undefined, which is an unintentional absence of any object value. That is becau
4 min read
How to check the given path is file or directory in node.js ? Sometimes there is a need to check whether the given path is a file or directory so that different operations can be performed based on the result. For instance, to log the information of the directory and file separately. In Node.js, file handling is handled by the fs module. You can read more abo
4 min read
How to Show the Line which Cause the Error in Node.js ? Debugging is a critical part of software development. When an error occurs in a Node.js application, understanding exactly where it happened is essential for diagnosing and fixing the problem. Node.js provides several ways to pinpoint the line of code that caused an error. This article explores thes
4 min read