Skip to content
jshacks.dev
Fundamentals

How to Check If an Object Is Empty in JavaScript Safely

Check for an empty object with Object.keys(obj).length === 0 after guarding null. See symbol keys, inherited properties, Date and Map traps and for in.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, Vite and TypeScript logos.

An empty object is {}, and checking for one sounds trivial until you try. The obvious tests give wrong answers in the cases that matter: obj === {} is always false, if (obj) is always true, comparing JSON.stringify to "{}" is slow and wrong for several values, and Object.keys() throws on null. The check that works for a plain object is one line, Object.keys(obj).length === 0, and its limits are worth knowing, since "empty" depends on what you count: symbol keys, non-enumerable properties and inherited ones are all invisible to Object.keys(), and objects that are not plain objects, such as dates and maps, report no keys while holding data. This post shows the right check, why the tempting ones fail, how to cover symbols and other special cases, how to restrict the test to plain objects, and the mistakes that get past review. The examples run on Node.js 24.

The short answer

JavaScript
const isEmpty = (object) => Object.keys(object).length === 0;

console.log(isEmpty({}), isEmpty({ a: 1 }), isEmpty({ a: undefined }), isEmpty([]), isEmpty(""));
Text
true false false true true

Object.keys() returns an array of an object's own enumerable string keys, and the object is empty if there are none. A property whose value is undefined still counts, since the key exists, as the third result shows. The last two results show a hazard: an empty array and an empty string also report true, because they have no own enumerable keys either. If the input can be something other than a plain object, add a type check, as a later section shows.

Why the tempting checks fail

JavaScript
const object = {};

console.log(object === {}, Boolean(object), object == false);
console.log(JSON.stringify(object) === "{}");
console.log(JSON.stringify({ a: undefined, b() {} }) === "{}");
console.log(JSON.stringify({ [Symbol("s")]: 1 }) === "{}");
Text
false true false
true
true
true

Two objects are never equal under ===, since objects compare by identity, so object === {} is false even when the object is empty. An empty object is truthy, so Boolean(object) is true. The JSON.stringify comparison works for the plain case and gives the wrong answer for an object whose only properties are undefined, functions or symbols, because JSON omits them: both objects in the last two lines report as empty and are not. It also builds a string just to compare it, and throws for circular references and BigInt values. Do not use it for this.

null and undefined

Object.keys() throws on null and undefined, so guard first.

JavaScript
try {
  Object.keys(null);
} catch (error) {
  console.log(error.name);
}

const isEmptyObject = (value) => value != null && typeof value === "object" && Object.keys(value).length === 0;

console.log(isEmptyObject({}), isEmptyObject(null), isEmptyObject(undefined), isEmptyObject({ a: 1 }));
console.log(isEmptyObject(0), isEmptyObject("text"), isEmptyObject(() => {}));
Text
TypeError
true false false false
false false false

The condition value != null covers both null and undefined, which is the one place loose equality is idiomatic. The typeof check keeps numbers, strings and functions from being called "empty objects": Object.keys(0) returns [], so without the guard a number would report as an empty object. Decide what you want for missing input: here both null and undefined give false, and some code treats them as empty, so write the rule you need.

Symbols, non-enumerable and inherited properties

Object.keys() sees only own, enumerable, string-named properties.

JavaScript
const withSymbol = { [Symbol("id")]: 1 };
const hidden = Object.defineProperty({}, "secret", { value: 1, enumerable: false });
const child = Object.create({ inherited: true });

console.log(Object.keys(withSymbol).length, Object.keys(hidden).length, Object.keys(child).length);

console.log(Reflect.ownKeys(withSymbol).length, Reflect.ownKeys(hidden).length, Reflect.ownKeys(child).length);

console.log("inherited" in child, Object.hasOwn(child, "inherited"));

const trulyEmpty = (value) => Reflect.ownKeys(value).length === 0;
console.log(trulyEmpty({}), trulyEmpty(withSymbol), trulyEmpty(hidden), trulyEmpty(child));
Text
0 0 0
1 1 0
true false
true false false true

All three objects look empty to Object.keys(). The first has a symbol key, the second a property that is hidden from enumeration, and the third an inherited property. Reflect.ownKeys() returns every own key, string and symbol, enumerable or not, so it counts the first two. The inherited property is not an own property by definition, and Object.keys() and Reflect.ownKeys() agree to ignore it. Which of these counts as "empty" depends on the use. For data that came from JSON or a form, Object.keys() is right. For a configuration object that may carry symbols, use Reflect.ownKeys().

for...in and why it is not the same

A for...in loop visits inherited enumerable properties too, so an early-exit loop needs an ownership check.

JavaScript
function isEmptyWithLoop(object) {
  for (const key in object) {
    if (Object.hasOwn(object, key)) return false;
  }
  return true;
}

const base = { inherited: 1 };
const child = Object.create(base);

console.log(isEmptyWithLoop({}), isEmptyWithLoop({ a: 1 }), isEmptyWithLoop(child));

function isEmptyNoCheck(object) {
  for (const key in object) return false;
  return true;
}

console.log(isEmptyNoCheck(child));
Text
true false true
false

The loop version stops at the first own key without building an array, which can matter for objects with very many properties, and we do not quote a figure because it depends on the engine and the object. Without the Object.hasOwn() check, the inherited property makes isEmptyNoCheck(child) report false, though the child has no properties of its own. For most code, the one-line Object.keys() version is clearer, and the loop is worth it only on a hot path.

Objects that are not plain

Many built-in objects keep their data in places that Object.keys() cannot see.

JavaScript
const things = [
  ["{}", {}],
  ["Date", new Date()],
  ["Map", new Map([["a", 1]])],
  ["Set", new Set([1])],
  ["RegExp", /a/],
  ["Error", new Error("x")],
  ["function", () => {}],
];

for (const [label, value] of things) {
  console.log(label.padEnd(8), Object.keys(value).length === 0);
}
Text
{}       true
Date     true
Map      true
Set      true
RegExp   true
Error    true
function true

Every one of them reports as empty, and only the first is. A Date holds a time, a Map and a Set hold entries, and an Error has a non-enumerable message. If a function accepts "an object" and may receive these, check that it is a plain object first.

JavaScript
const isPlainObject = (value) => {
  if (value === null || typeof value !== "object") return false;
  const prototype = Object.getPrototypeOf(value);
  return prototype === Object.prototype || prototype === null;
};

const isEmptyPlainObject = (value) => isPlainObject(value) && Object.keys(value).length === 0;

console.log(isEmptyPlainObject({}), isEmptyPlainObject(Object.create(null)), isEmptyPlainObject(new Date()));
console.log(isEmptyPlainObject(new Map()), isEmptyPlainObject([]), isEmptyPlainObject(new (class A {})()));
Text
true true false
false false false

A plain object has Object.prototype or null as its prototype. The check accepts objects created by a literal, by new Object() and by Object.create(null), and rejects dates, maps, arrays and instances of classes. For collections, use their own size: map.size === 0, set.size === 0 and array.length === 0.

Emptiness across types

A function that works with "any empty value" needs to handle each kind.

JavaScript
function isEmptyValue(value) {
  if (value == null) return true;
  if (typeof value === "string" || Array.isArray(value)) return value.length === 0;
  if (value instanceof Map || value instanceof Set) return value.size === 0;
  if (typeof value === "object") return Reflect.ownKeys(value).length === 0;
  return false;
}

console.log([null, "", [], new Map(), {}, 0, false, "a", [0], { a: 1 }].map(isEmptyValue).join(" "));
Text
true true true true true false false false false false

Each branch uses the right test for its type, and the numbers 0 and false are not considered empty, which is a choice: a library such as Lodash makes _.isEmpty(0) return true, and you may not want that. Write the rule you mean, and name the function for it, such as isBlank or hasNoEntries.

A mistake we hit: the empty object that was not empty

JavaScript
const options = { timeout: undefined, retries: undefined };

console.log(Object.keys(options).length === 0);
console.log(Object.values(options).every((v) => v === undefined));
console.log(JSON.stringify(options));

function withDefaults(settings) {
  if (Object.keys(settings).length === 0) return { timeout: 30, retries: 3 };
  return settings;
}

console.log(withDefaults(options));
Text
false
true
{}
{ timeout: undefined, retries: undefined }

A caller built an options object by copying values from a form, where unset fields were undefined. The object had keys, so it was not empty, and the defaults were skipped: the code ran with undefined for both options. The JSON text, {}, looked empty, which is where the confusion came from. We now decide on meaning: an options object is "unset" if every value is undefined, and we apply defaults per field with ?? instead of a single emptiness check.

Choosing between the checks

You want to knowUse
A plain object has no enumerable own propertiesObject.keys(value).length === 0
It has no keys of any kind, including symbolsReflect.ownKeys(value).length === 0
The value is a plain object, and emptyisPlainObject(value) && Object.keys(value).length === 0
A hot path with large objectsA for...in loop with Object.hasOwn() and early return
A Map or Set is empty.size === 0
An array or string is empty.length === 0
All values unsetObject.values(value).every((v) => v === undefined)

Practical rules we follow

Guard null and undefined before calling Object.keys(). Decide whether symbols and hidden properties count. Use a plain-object check when the input type is open. Never compare to {} or use JSON.stringify. Use .size and .length for collections. Treat undefined values as present unless you say otherwise. And give the function a name that states the rule.

Where this check stops

Object.keys() cannot tell you whether the object has a prototype chain with data, whether a Proxy hides its keys, or whether a getter on the prototype would return something. A frozen empty object is still empty. Class instances with private fields, declared with #, can look empty and hold state that no key reveals. The reference is in the MDN Object.keys page and the MDN Reflect.ownKeys page.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.