Codementor Events

Object.keys() in javascript

Published Dec 11, 2018
Object.keys()  in javascript

Get the keys with object.keys()

The Object.keys() method returns an array of a given object's own property names.

The keys in the returned will be in the same order as we get with a normal loop.

EXAMPLE

const obj = {
          name :"john",
          age :22
          };

console.log(Object.keys(obj));

//[name, age]

Syntax

Object.keys(obj)

Parameter

obj

  • The object of which the enumerable's own properties are to be returned.
  • If we pass empty object then return empty array
  • If we don’t pass any argument then it throws error

Return value

An array of strings that represent all the enumerable properties of the given object.

var array = ['a', 'b', 'c'];

console.log(Object.keys(array)); // ['0', '1', '2']

var funObj = {
      fun : function () {
                ...
      }
}
console.log(Object.keys(funObj)) // ["fun"]

Note :

When we pass non-object except undefined and will be coerced to an object.

Object.keys(123) // []

Object.keys(123.34) // []

Object.keys("hi") // ["0" , "1"]
Discover and read more posts from jagathish
get started
post commentsBe the first to share your opinion
Shawn
5 years ago

I didn’t know this! Thank you.

TechiePriyaRanjan
5 years ago

Thanks for this great article 👌, meanwhile could you please elucidate this line,
“When we pass non-object except undefined and will be coerced to an object.” , please give example of undefined. (I’m new in #JSWorld)

jagathish
5 years ago

which means when we pass 123 which is not an object then it is converted to an object (an array Object).

Object.keys(123) // []

Object.keys(“123”) . // [“0”, “1”, “2”]

Show more replies