Home > Back-end >  Why passing function object to Object.keys() returns empty array?
Why passing function object to Object.keys() returns empty array?

Time:08-15

So, functions in js are objects with some keys, right? I'm trying to iterate through them, but i'm getting empty list:

function f(a) {
console.log(Object.keys(f)) //prints []
console.log(f.arguments) //key "arguments" exists and prints Arguments object
}

Any expanation why Object.keys() doesn't return keys for function object?

CodePudding user response:

Object.keys will only list enumerable properties. The arguments property is not enumerable, as you can see if you use getOwnPropertyDescriptor.

The property exists, but

function f() {

}
console.log(Object.getOwnPropertyDescriptor(f, 'arguments'));

To get a list of all own-property keys (excluding symbols), including non-enumerable ones, you can use Object.getOwnPropertyNames.

function f() {

}
console.log(Object.getOwnPropertyNames(f));

which, here, gives you

[
  "length",
  "name",
  "arguments",
  "caller",
  "prototype"
]

Object.keys could have returned properties if any properties put directly on the function were enumerable, such as

function f() {

}
f.someProp = 'foo';
console.log(Object.keys(f));

  • Related