object check null or empty

Object Check Null or Empty

Checking whether an object is null or empty is a common scenario in programming. There are several ways to do this in JavaScript:

Method 1: Using the if statement

The simplest and most straightforward way to check if an object is null or empty is by using the if statement. Here's an example:


let myObj = {};
if(myObj == null || Object.keys(myObj).length === 0){
    console.log("Object is empty or null");
} else {
    console.log("Object is not empty or null");
}

In the above example, we first check if the object is null or undefined using the nullish coalescing operator. Then, we check if the object has any properties using the Object.keys() method. If the object is empty, then the length of the array returned by Object.keys() will be zero.

Method 2: Using the lodash library

The lodash library provides a convenient way to check if an object is empty or null. Here's an example:


const _ = require('lodash');
let myObj = {};
if(_.isEmpty(myObj)){
    console.log("Object is empty or null");
} else {
    console.log("Object is not empty or null");
}

In the above example, we use the _.isEmpty() method provided by the lodash library to check if the object is empty.

Method 3: Using the ternary operator

The ternary operator provides a concise way to check if an object is empty or null. Here's an example:


let myObj = {};
let result = (myObj == null || Object.keys(myObj).length === 0) ? "Object is empty or null" : "Object is not empty or null";
console.log(result);

In the above example, we use the ternary operator to check if the object is empty or null. If it is, then we assign the string "Object is empty or null" to the variable result. Otherwise, we assign the string "Object is not empty or null" to the variable result.

Method 4: Using the try-catch block

Another way to check if an object is null or empty is by using the try-catch block. Here's an example:


let myObj = {};
try {
    JSON.stringify(myObj);
    console.log("Object is not empty or null");
} catch (e) {
    console.log("Object is empty or null");
}

In the above example, we try to convert the object to a JSON string using the JSON.stringify() method. If the object is empty or null, then an exception will be thrown and caught in the catch block. Otherwise, we know that the object is not empty or null.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe