An Overview of the Object.keys() Function in JavaScript

Jun 26, 2019

The Object.keys() function returns an array of the property names an object has. For example, given a POJO obj, calling Object.keys() gives you all the object's keys.

const obj = {
  name: 'Jean-Luc Picard',
  age: 59,
  rank: 'Captain'
};
Object.keys(obj); // ['name', 'age', 'rank']

Key Order

The property names are in the order the property was first set. If you delete a property and then later set it again, the property goes to the end of the array.

const obj = {
  name: 'Jean-Luc Picard',
  age: 59
};

obj.rank = 'Captain';
Object.keys(obj); // ['name', 'age', 'rank']

delete obj.age;
obj.age = 59;
Object.keys(obj); // ['name', 'rank', 'age']

The ECMAScript spec calls this "property creation order". The Object.keys() function is guranteed to return keys in property creation order in all ES2015-compliant environments. There is one key exception: numeric keys.

Any property name that is an integer between 0 and 2^32 - 1 inclusive will come before all non-integer keys, and these properties will be sorted in numeric order.

const obj = {
  name: 'Jean-Luc Picard',
  rank: 'Captain',
  1: 'test',
  100: 'test',
  10: 'test'
};

Object.keys(obj); // ['1', '10', '100', 'name', 'rank']

ES6 Classes

The Object.keys() function only returns so-called "own properties.". That means Object.keys() will not return class methods or class properties.

class Character {
  get show() { return 'Star Trek: The Next Generation'; }

  firstName() {
    return this.name.slice(0, this.name.indexOf(' '));
  }
}

const obj = new Character();
Object.assign(obj, {
  name: 'Jean-Luc Picard',
  age: 59,
  rank: 'Captain'
});

obj.show; // 'Star Trek: The Next Generation'
obj.firstName(); // 'Jean-Luc'

// `show` and `firstName` are **not** own properties, because they're
// from the class
Object.keys(obj); // ['name', 'age', 'rank']

// But if you overwrite a class property, it becomes an own property.
obj.firstName = () => 'test';
Object.keys(obj); // ['name', 'age', 'rank', 'firstName']

Symbols

The Object.keys() property does not include symbol properties. You need to use Object.getOwnPropertySymbols() to get symbol properties.

const rankSymbol = Symbol('rank');

const obj = {
  name: 'Jean-Luc Picard',
  age: 59,
  [rankSymbol]: 'Captain'
};

Object.keys(obj); // ['name', 'age']
Object.getOwnPropertySymbols(obj); // [ Symbol(rank) ]

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!