Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why passing function object to Object.keys() returns empty array?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading