Skip to content

Object.keys(): list an object's own keys (ES5)

  • Which keys Object.keys() returns, which it skips, and in what order.
  • How it treats arrays, primitives, null and undefined.
  • How to use it for allow-list validation of request bodies.
  • Why TypeScript types the result as string[], and which alternative to use when you need more keys.

TL;DR: Object.keys(obj) returns a new array of the object’s own, enumerable, string-keyed property names. Inherited properties, non-enumerable properties and symbol keys are left out. Integer-like keys come first in ascending order, then the other string keys in insertion order.

It was added in ECMAScript 5 (2009) and works in every browser and runtime still in use (details in Compatibility). Its siblings Object.values() and Object.entries() (ES2017) use the same rules to return values and key-value pairs.

Before ES5, the only built-in way to list keys was a for...in loop, which also visits inherited enumerable properties. Every loop needed a hasOwnProperty filter, and forgetting it leaked prototype properties into the result. The settings object below, from an invented OrdersPortal app, inherits its defaults.

Running the samples: save a sample as a .mjs file and run it with Node.js 22 (node sample.mjs), or paste it into a browser console. All outputs shown were produced with Node.js 22.23.

const defaults = { currency: 'USD', pageSize: 25 };
const settings = Object.create(defaults); // inherits currency and pageSize
settings.theme = 'dark';
settings.locale = 'en-US';
// The for...in pattern: it walks the prototype chain, so you had to filter.
const before = [];
for (const key in settings) {
if (Object.prototype.hasOwnProperty.call(settings, key)) before.push(key);
}
console.log(before);
// ES5: own, enumerable, string keys only.
console.log(Object.keys(settings));

Output:

[ 'theme', 'locale' ]
[ 'theme', 'locale' ]

Object.keys() gives the same answer in one expression, as a real array.

// Fragment: signature
const keys = Object.keys(obj); // string[]

The spec algorithm is ToObject(obj), then EnumerableOwnProperties(obj, key), wrapped in a new array. That gives these rules:

  • Own, string, enumerable only. No prototype chain, no symbol keys, and no non-enumerable properties (such as those created by Object.defineProperty with default attributes, or an array’s length).
  • Order. Keys that are array indices (canonical integers from 0 to 2³² − 2) come first in ascending numeric order, then the remaining string keys in the order they were created. '-1' and '01' are not array indices, so they stay in insertion order.
const sku = Symbol('sku');
const order = { status: 'paid', 10: 'ten', id: 'o-1001', 2: 'two', [sku]: 'A-77', '-1': 'minus', '01': 'zero-one' };
Object.defineProperty(order, 'internalNote', { value: 'fraud check passed', enumerable: false });
console.log(Object.keys(order));
console.log(Object.getOwnPropertyNames(order).includes('internalNote')); // non-enumerable
console.log(Reflect.ownKeys(order).length); // every own key, symbols included
console.log(Object.keys('ab')); // strings have index keys
console.log(Object.keys(42)); // other primitives: none
console.log(Object.keys(['x', , 'z'])); // holes are skipped
try {
Object.keys(null);
} catch (error) {
console.log(error.constructor.name, '-', error.message);
}

Output:

[ '2', '10', 'status', 'id', '-1', '01' ]
true
8
[ '0', '1' ]
[]
[ '0', '2' ]
TypeError - Cannot convert undefined or null to object

Two pieces of history: in ES5 any primitive argument threw a TypeError (since ES2015 primitives are boxed, and only null and undefined throw), and until ES2020 the spec left the order implementation-defined. ES2020 tied it to the own-keys order above, which engines already used. Error messages are V8’s wording.

Object.keys() is declared in lib.es5.d.ts as keys(o: object): string[], not (keyof T)[]. This is deliberate: TypeScript’s object types are open, so a value typed { id: string } may carry extra properties at run time, and keyof T would be a lie.

// Fragment
interface OrderSummary { id: string; total: number }
function printSummary(summary: OrderSummary) {
for (const key of Object.keys(summary)) {
// summary[key]; // strict mode, TS7053: 'string' can't be used to index type 'OrderSummary'
}
// Narrow explicitly when you know the object is closed:
for (const key of Object.keys(summary) as (keyof OrderSummary)[]) {
console.log(key, summary[key]);
}
}

Checked with tsc --strict on TypeScript 6.0.3. Only cast when the object is known to have no extra keys; otherwise prefer Object.entries() or a const array of known keys.

OrdersPortal lets customers edit a few fields of an order with a PATCH request. The handler must reject an empty body and any field that is not on an allow-list:

// OrdersPortal: validate a PATCH body against an allow-list of fields.
const EDITABLE = new Set(['shippingAddress', 'notes', 'giftWrap']);
function validatePatch(body) {
const keys = Object.keys(body);
if (keys.length === 0) return { ok: false, error: 'empty patch' };
const unknown = keys.filter((key) => !EDITABLE.has(key));
if (unknown.length > 0) return { ok: false, error: `not editable: ${unknown.join(', ')}` };
return { ok: true, fields: keys };
}
console.log(validatePatch({}));
console.log(validatePatch({ notes: 'Leave at door', giftWrap: true }));
console.log(validatePatch(JSON.parse('{"notes":"hi","status":"refunded","__proto__":{"isAdmin":true}}')));

Output:

{ ok: false, error: 'empty patch' }
{ ok: true, fields: [ 'notes', 'giftWrap' ] }
{ ok: false, error: 'not editable: status, __proto__' }

In the last case, JSON.parse creates __proto__ as an ordinary own property (it does not set the prototype), so Object.keys() reports it and the allow-list rejects it. An allow-list, unlike a block-list, also stops fields nobody anticipated.

  • Expecting class methods or getters. They live on the prototype, so Object.keys(new Order()) lists only instance fields.
  • Relying on insertion order for numeric keys. { 10: 'a', 2: 'b' } lists '2' first. For ordered IDs such as '1001', use an array or a Map.
  • Calling it on a Map or Set. Their entries are internal data, not properties, so Object.keys(new Map([['a', 1]])) is []. Use map.keys().
  • Emptiness checks on huge objects in hot paths. Object.keys(obj).length === 0 builds a full array first. Fine for request bodies; wasteful in a tight loop over large objects.
  • Forgetting null. Object.keys(maybeData) throws when the value is null or undefined. Guard with Object.keys(maybeData ?? {}).
Need Use
Own enumerable string keys Object.keys(obj)
Own string keys, including non-enumerable Object.getOwnPropertyNames(obj)
Every own key, symbols included Reflect.ownKeys(obj)
Own and inherited enumerable keys for...in
Does one specific key exist? Object.hasOwn(obj, key), not Object.keys(obj).includes(key)
Values, or key-value pairs Object.values(), Object.entries()

Use Object.keys() for plain data objects such as JSON payloads and configuration. Use a Map when keys change often, are not strings, or must keep insertion order even when numeric.

According to MDN’s browser compatibility data, Object.keys() is supported in Chrome 5, Edge 12, Firefox 4, Safari 5 (including iOS), Internet Explorer 9, Node.js 0.10, Deno 1.0 and Bun 1.0. No polyfill or TypeScript lib setting is needed in any current project.

1. What does Object.keys() return for Object.create({ a: 1 }) with an own property b? ['b']. It lists only own, enumerable, string keys; a is inherited. for...in would visit both.

2. In what order are the keys returned, and is it guaranteed? Array-index keys in ascending numeric order, then other string keys in creation order; never symbols. The spec has guaranteed this order for Object.keys(), Object.values(), Object.entries() and JSON.stringify() since ES2020.

3. Senior scenario: an API accepts JSON bodies and copies them onto stored records. How do you use key enumeration safely? Validate Object.keys(body) against a per-endpoint allow-list, reject unknown keys (including __proto__ and constructor), copy only allow-listed keys onto a fresh object, and validate each value’s schema. Never feed request bodies to a recursive merge that writes through __proto__: that is how prototype pollution happens.

  • Object.keys() (ES5) returns a fresh array of own, enumerable, string keys: array indices first, then insertion order.
  • Primitives are boxed since ES2015; null and undefined throw.
  • Validate untrusted input against an allow-list of keys; use Object.hasOwn() for single-key checks.
  • In TypeScript the result is string[] by design.