Unlike arrays, plain JavaScript objects do not have a .length property. To count how many properties an object has, pass the object to Object.keys(obj) and read .length on the returned array.


1. Counting Own Enumerable String Keys with Object.keys()

Object.keys() returns an array of an object’s own enumerable string property names, so .length gives you the exact count:

const user = { id: 42, name: "Tariq", active: true };
const keyCount = Object.keys(user).length;

console.log(keyCount); // 3
console.log(Object.keys({}).length); // 0

2. Counting Symbol Keys or Non-Enumerable Properties

By default, Object.keys() skips symbol keys and non-enumerable properties. Use specialized static methods when you need those included:

const sym = Symbol("internalId");
const record = { title: "Draft", [sym]: 99 };

Object.defineProperty(record, "hiddenFlag", {
  value: true,
  enumerable: false
});

console.log(Object.keys(record).length); // 1 ("title")
console.log(Object.getOwnPropertyNames(record).length); // 2 ("title", "hiddenFlag")
console.log(Reflect.ownKeys(record).length); // 3 (includes symbol key too)

3. Edge Cases and Better Data Structures

  • Null or non-object inputs: Calling Object.keys(null) or Object.keys(undefined) throws a TypeError. Guard with a nullish/type check if inputs may be nullable.
  • Nested objects are not counted recursively: Object.keys(obj).length only counts top-level keys on that specific object.
  • Frequent size checks or dynamic keys: If you add and remove keys constantly and check size often, Map has a built-in .size property and avoids prototype key collisions.

TL;DR: Use Object.keys(obj).length for standard own string keys, Reflect.ownKeys(obj).length if you also need symbol or non-enumerable keys, and consider Map when you need frequent .size lookups.

Are you checking top-level keys on a plain object, counting nested properties, or managing dynamic key-value pairs?