Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Object

Object.keys()

Reference for JavaScript Object.keys(): list an object's own enumerable property names, key order rules, counting properties and looping with examples.

Object.keys() returns an array of the names of an object's own, enumerable properties whose keys are strings. It is the standard way to find out what an object contains, count its properties, or loop over them.

The names come back as strings, even for numeric keys. For the values use Object.values(), and for both together use Object.entries().

JavaScript
Object.keys({ a: 1, b: 2 }); // ["a", "b"]

Try it

JS Listing and counting keys

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Order, hidden and inherited keys

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
Object.keys(obj)
Name Description
obj The object whose own enumerable string keys are returned. Primitives are converted to objects.

Return value: a new array of strings.

Exceptions: a TypeError if obj is null or undefined.

Usage notes

  • Own and enumerable only. Inherited properties, properties made non-enumerable and symbol keys are left out. for...in also visits enumerable inherited properties.
  • Predictable order. Integer-like keys come first in ascending numeric order; other keys follow in the order they were added.
  • Keys are strings. Object.keys([5, 6]) gives ["0", "1"]. Convert with Number() if you need numbers.
  • Counting: Object.keys(obj).length is the usual way to count properties. A property whose value is undefined still counts.
  • A snapshot. Adding or removing properties later does not change the array already returned.
  • Maps and Sets are not affected: their entries are not properties, so Object.keys(new Map([[1, 2]])) is []. Use map.keys().
  • Hidden members: Object.getOwnPropertyNames() includes non-enumerable ones, and Reflect.ownKeys() adds symbols.
  • Cost: it creates a new array on each call. Store the result when you need it more than once.

Browser support

Object.keys() is available in every browser and JavaScript runtime.