2

Hey guys I'm kind of new to JS and found out that functions are also objects. This means I can add properties to them like this:

 let func = function(){};
 func.foo = "foo";
 console.log(func.foo); // prints foo

However when we now do this:

console.log(func);

It will return (using chrome):

enter image description here

Why does it not show the properties of the object like it usually shows on other type of objects? Also when we for instance try to console.log(Function) it will return the following output:

enter image description here

What is this native code? What I got from other sources was that it is code written in another programming language(C, C++) that programmed the functionality of this constructor.

Thanks in advance!

5
  • 3
    Because that's how Google Chrome's console logs elements of type function. Commented Sep 14, 2017 at 22:14
  • 1
    ... If you want it to show up like an object (so you can see its properties) then use dir instead of log: console.dir(func); Commented Sep 14, 2017 at 22:15
  • @ibrahimmahrir you could also do console.log(Object.assign({}, func)); Commented Sep 14, 2017 at 22:27
  • @PatrickRoberts but that will copy the properties into another object. It won't the function. console.log([ func ]); will do fine (an array that contain the function, the function will be listed like an object not as code source). Commented Sep 14, 2017 at 22:29
  • @ibrahimmahrir I'm well aware of what my approach does, but the request was to log the properties, which is exactly what it does. Commented Sep 14, 2017 at 22:31

1 Answer 1

4

Chrome’s console displays functions’ bodies instead of their properties, because that’s usually more useful. It’s much easier to tell when you don’t use an empty function:

Screenshot of non-empty function in Chrome console

And it’ll indeed substitute in [native code] when there is no JavaScript body to be shown.

As @ibrahim mahrir points out, you can use console.dir(func) to get both the default inspection and an expandable list of properties.

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.