How do you reliably check if an object is empty?
JavaScriptThe short answer
The most reliable way is Object.keys(obj).length === 0. This counts the object's own enumerable properties. If it is zero, the object is empty. Make sure you also check that the value is actually an object and not null.
The standard approach
function isEmpty(obj) { return Object.keys(obj).length === 0;}isEmpty({}); // trueisEmpty({ name: 'John' }); // falseHandling edge cases
null and undefined are not objects, so check for them first:
function isEmpty(obj) { return ( obj != null && typeof obj === 'object' && Object.keys(obj).length === 0 );}isEmpty({}); // trueisEmpty(null); // falseisEmpty(undefined); // falseisEmpty([]); // true — arrays are objects with 0 keysIf you want to exclude arrays:
function isEmptyObject(obj) { return ( obj != null && typeof obj === 'object' && !Array.isArray(obj) && Object.keys(obj).length === 0 );}Why not just use if (obj)
const obj = {};if (obj) { console.log('This runs!'); // empty objects are truthy}An empty object {} is truthy in JavaScript. So if (obj) does not tell you if the object has properties — it only tells you the value is not null, undefined, 0, '', or false.
Other approaches
// JSON.stringify — works but slowerJSON.stringify(obj) === '{}';// for...in — slightly more verbosefunction isEmpty(obj) { for (const key in obj) { if (obj.hasOwnProperty(key)) return false; } return true;}Object.keys().length is the cleanest and most widely used approach.
Interview Tip
Lead with Object.keys(obj).length === 0. Mention the null check as an edge case. If the interviewer asks why you cannot just use if (obj), explain that empty objects are truthy in JavaScript.
Why interviewers ask this
This tests fundamental JavaScript knowledge about objects, truthiness, and the Object API. It is a quick question that reveals how well you understand JavaScript's type system.