A Function
in JavaScript can be referred to as "first class" as it is a callable object meaning it is an object with callable semantics added to it. In some ways an Array
in JavaScript is similar to a Function
in that they are both objects but have special features included. NOTE: A common statement uttered about JavaScript is that "everything is an object" but this is not true however. None of the simple primitives (string
, boolean
, number
, null
, and undefined
) are objects (although JS does some nifty tricks if you attempt to treat them as such).
var obj = {bar: 'hi'};
Object.keys(obj); // ["bar"]
function func() {}
Object.keys(func); // []
func.bar = 'hello';
Object.keys(func); // ["bar"];
var arr = [1, 2, 3];
Object.keys(arr); // ["0", "1", "2"]
arr.bar = 'hey';
Object.keys(arr); // ["0", "1", "2", "bar"]
bar
shows up in all three because those properties are set to be enumerable by default. However as you noted a function has some other properties but those aren't showing up. Why? Let's look at obj
first.
obj.propertyIsEnumerable('bar'); // true
bar
by default was set to be enumerable
.
Now lets look at bar
in func
.
func.propertyIsEnumerable('bar'); // true
So that explains why bar
shows up for func
but what about name
?
func.propertyIsEnumerable('name'); // false
Ahah! It is not enumerable. This is true for a lot of properties/methods that are automatically linked to or assigned to an object via the JavaScript engine. For instance, the length
property of an array object.
arr.propertyIsEnumerable('length'); // false
That all said, if you are new to JS I would highly recommend reading the You Don't Know JS series by Kyle Simpson. It's meant for people with some programming experience but they are very useful for learning what JS is and what it's not (no matter how much syntactic sugar gets piled on). I would especially recommend focusing on the key point of the difference between classical inheritance and JavaScript's OLOO (Objects Linking to Other Objects).
The intro book Up & Going is a quick read that covers the basics of what the entire series will dive deeper into. The rest of the series (so far) includes: Types & Grammar, Scopes & Closures, this & Object Prototypes, Async & Performance, and ES6 & Beyond. You can also preview them all on his github repository.
OR You can also review MDN's documentation for Working with Objects for some very good information.