0

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
The worm
  • 5,580
  • 14
  • 36
  • 49
  • @JJJ I saw it and tried to find a better duplicate but couldn't. That question is pretty different from this one. If you find a better duplicate I'm definitely in favor of dupehammering. – Benjamin Gruenbaum Oct 28 '16 at 14:08

3 Answers3

3

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.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
1

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));
mhodges
  • 10,938
  • 2
  • 28
  • 46
0

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

Omegastick
  • 1,773
  • 1
  • 20
  • 35