Borislav Hadzhiev
Tue Oct 05 2021·2 min read
Photo by MusicFox Fx
To check if an object is empty in JavaScript:
Object.keys
method to get an array of all the keys
of the objectlength
property on the array0
, if it is, then the object is
empty// Supported in IE 9-11 const obj = {}; const isEmpty = Object.keys(obj).length === 0; console.log(isEmpty); // 👉️ true
In the code example, we used the Object.keys method to get an array of all of the keys of the object.
Object.keys
method returns an empty array if the object has no key-value pairs (if it's empty).Here's what calling Object.keys
on a non-empty object looks like.
const obj = {a: 1, b: 2}; console.log(Object.keys(obj)); // 👉️ ['a', 'b'] const isEmpty = Object.keys(obj).length === 0; console.log(isEmpty); // 👉️ false
An alternative approach is to try to iterate over the properties of the object. If there is even a single iteration, then the object is not empty.
// Supported in IE 6-11 const obj = {}; function isEmpty(object) { for (const property in object) { return false; } return true; } console.log(isEmpty(obj)); // 👉️ true
In the code snippet, we have created a helper function which attempts to iterate over the properties of an object.
If there is even 1
iteration, we know that the object has at least 1
key-value pair and is not an empty object.
If there aren't any iterations, then the object is empty.