0

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?

1
  • Btw, f.arguments should not exist, it's deprecated and accessing it in strict mode will throw Commented Aug 14, 2022 at 22:33

1 Answer 1

2

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));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.