How do you check if an object is empty?
An object is "empty" when it has no own enumerable properties.
Object.keys(obj).length === 0 — the simplest, most common check.
Guard first — confirm it's a plain object (not null or another type).
Alternative — Object.entries(obj).length === 0 works too.
Don't use obj === {} — two different objects are never strictly equal, so it's always false.
const empty = {};
const notEmpty = { key: 'value' };
// Method 1: Object.keys (recommended)
console.log(Object.keys(empty).length === 0); // true
console.log(Object.keys(notEmpty).length === 0); // false
// Method 2: JSON.stringify
console.log(JSON.stringify(empty) === '{}'); // true
// Method 3: for...in (fastest for non-empty)
function isEmpty(obj) {
for (const key in obj) {
if (obj.hasOwnProperty(key)) return false; // Found a property
}
return true;
}
// Utility function
function isEmptyObject(obj) {
return obj !== null
&& typeof obj === 'object'
&& !Array.isArray(obj)
&& Object.keys(obj).length === 0;
}
console.log(isEmptyObject({})); // true
console.log(isEmptyObject({ a: 1 })); // false
console.log(isEmptyObject([])); // false (array, not object)
console.log(isEmptyObject(null)); // falseObject.keys returns own enumerable property names — length 0 means empty. The utility function adds null/array checks for robustness. for...in with hasOwnProperty short-circuits on the first found property (slightly faster for large non-empty objects).
JSON.stringify works but is overkill.
Object.keys(obj).length === 0 is the standard answer. Know edge cases: null is not an empty object, arrays are not empty objects.
The for...in approach for performance-sensitive code. The utility function with null/array checks shows thoroughness.