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

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);

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); delete obj.age; obj.age = 59 ; Object .keys(obj);

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);

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; obj.firstName(); Object .keys(obj); obj.firstName = () => 'test' ; Object .keys(obj);

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); Object .getOwnPropertySymbols(obj);

More Fundamentals Tutorials