Object.keys(): list an object's own keys (ES5)
What you’ll learn
Section titled “What you’ll learn”- Which keys
Object.keys()returns, which it skips, and in what order. - How it treats arrays, primitives,
nullandundefined. - 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.
Summary
Section titled “Summary”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.
The problem it solves
Section titled “The problem it solves”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 pageSizesettings.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.
How it works
Section titled “How it works”// Fragment: signatureconst 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.definePropertywith default attributes, or an array’slength). - Order. Keys that are array indices (canonical integers from
0to 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-enumerableconsole.log(Reflect.ownKeys(order).length); // every own key, symbols included
console.log(Object.keys('ab')); // strings have index keysconsole.log(Object.keys(42)); // other primitives: noneconsole.log(Object.keys(['x', , 'z'])); // holes are skippedtry { Object.keys(null);} catch (error) { console.log(error.constructor.name, '-', error.message);}Output:
[ '2', '10', 'status', 'id', '-1', '01' ]true8[ '0', '1' ][][ '0', '2' ]TypeError - Cannot convert undefined or null to objectTwo 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.
TypeScript
Section titled “TypeScript”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.
// Fragmentinterface 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.
Realistic example
Section titled “Realistic example”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.
Common mistakes
Section titled “Common mistakes”- 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 aMap. - Calling it on a
MaporSet. Their entries are internal data, not properties, soObject.keys(new Map([['a', 1]]))is[]. Usemap.keys(). - Emptiness checks on huge objects in hot paths.
Object.keys(obj).length === 0builds 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 isnullorundefined. Guard withObject.keys(maybeData ?? {}).
When to use it and when not to
Section titled “When to use it and when not to”| 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.
Compatibility
Section titled “Compatibility”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.
Interview questions
Section titled “Interview questions”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.
Key takeaways
Section titled “Key takeaways”Object.keys()(ES5) returns a fresh array of own, enumerable, string keys: array indices first, then insertion order.- Primitives are boxed since ES2015;
nullandundefinedthrow. - Validate untrusted input against an allow-list of keys; use
Object.hasOwn()for single-key checks. - In TypeScript the result is
string[]by design.
Related pages
Section titled “Related pages”- Object.values() and Object.entries(): values and pairs, same rules.
- Object.hasOwn(): test one own property.
- Object.getOwnPropertyDescriptors(): every own property with its attributes.
- for…in: the loop that also walks the prototype chain.
- Symbol and Map and Set
- JavaScript interview questions
Official references
Section titled “Official references”- ECMAScript Language Specification,
Object.keys ( O )(current draft; first published in ECMAScript 5) - ECMAScript Language Specification,
EnumerableOwnPropertiesandOrdinaryOwnPropertyKeys - MDN: Object.keys()
- MDN: Enumerability and ownership of properties
- TypeScript 6.0.3:
lib.es5.d.ts