If JavaScript functions are first class objects and therefore of type object why does the below happen?
function hello(){}
typeof hello -> function
should it not give
typeof hello -> object
If JavaScript functions are first class objects and therefore of type object why does the below happen?
function hello(){}
typeof hello -> function
should it not give
typeof hello -> object
Yes, JavaScript functions are objects. The only base types in JavaScript are the primitive value types: number, symbol, boolean, null, undefined and string and objects.
Everything that is not a primitive value type is an object. typeof
is broken for other reasons, for example typeof null
is "object" but null is in fact not an object.
typeof hello
returns function because it's probably the only way to really be sure something can be called as a function.
In Javascript, if it's not a primitive, it's an object. Unfortunately, javascript does not distinguish very well between arrays, functions, and null when using the typeof
operator, but there are ways to tell by using Object.prototype.call()
Here is an example:
var a = function () {};
var b = null;
var c = [];
var d = {};
console.log("typeof function () {}: " + typeof a + " -- Object.prototype: " + Object.prototype.toString.call(a));
console.log("typeof null: " + typeof b + " -- Object.prototype: " + Object.prototype.toString.call(b));
console.log("typeof []: " + typeof c + " -- Object.prototype: " + Object.prototype.toString.call(c));
console.log("typeof {}: " + typeof d + " -- Object.prototype: " + Object.prototype.toString.call(d));
While Javascript functions are objects, so are numbers, strings, etc. The typeof function lets you know when the object is a specific data structure that Javascript already knows, and returns object if it's one that it doesn't know (but is still defined/not null).
There's more about this here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof