Understanding Object.keys()

Understanding Object.keys()

A quick guide to understanding `Object.keys()`

๐Ÿ‘‰ The Object.keys() method returns an array of a given object's own enumerable property names, or in simple words, the array of all the keys of an object.

๐Ÿ‘‰ Syntax

Object.keys(object)

๐Ÿ‘‰ Here are some of the major points you have to remember while using Object.keys()

  1. The ordering of the properties is the same as that given by looping over the properties of the object manually.

  2. In ES5, if the argument to this method is not an object (a primitive), then it will cause a TypeError.

  3. From ES2015 onwards, a non-object argument will be coerced to an object.

  4. If the properties have any numbered names, Object.keys will sort them.

๐Ÿ‘‰ Examples:

/** Simple usage  */

const user = {
  username:  'rehan-sattar',
  age: 22,
  isActive:   true
};
console.log(Object.keys(user)); 
// expected output: ["username", "age", "isActive"]

--------------------------------------------------------

/** Type Coercion  */

// In ES5
Object.keys('foo');  // TypeError: "foo" is not an object

// In ES2015+
Object.keys('foo');  // ["0", "1", "2"]

-------------------------------------------------------- 

/** Sorting keys example  */

const obj = { "greet": "Hi!", "1": "Byee", "0": "Oh!" };
Object.keys(obj);
// expected output:  ["0", "1", "greet"]

๐Ÿ‘‰ References:

The official MDN documentation of Object.keys()

๐Ÿ‘‰ Follow me:

ย