Thursday, December 13, 2018

Using Object.keys() in JavaScript


Object.keys(obj) returns the name property of the object which becomes handy to enumerate the property names, in the same order as returned with a normal loop.

     Input:
const myObject = {  name: 'somename',  age: 40,  gender: 'female'};
console.log(Object.keys(myObject));
     Output:
["name", "age", "gender"]

For non-object, the return type is an empty array.
     Input:
console.log(Object.keys(''));
     Output:
[]

For input of array type, it is the index of the array.

     Input:
console.log(Object.keys(['hello', 'hello2']));
     Output:
["0", "1"]
And for input of type string, the output is the array of the index for characters.
     Input:
console.log(Object.keys('hello2'));
     Output:
["0", "1", "2", "3", "4", "5"]

Syntax:
Object.keys(obj)
Parameter:
The object of which the enumerable's own properties are to be returned.
Return value:
An array of strings representing all the enumerable properties of the given object.
Exception:
Throws exception if parameter is not a valid object i.e.  null or undefined.





No comments:

Post a Comment