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
1
  • @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. Commented Oct 28, 2016 at 14:08

3 Answers 3

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.

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

3 Comments

cool cheers. so is typeof unsafe to use?
w3schools.com/js/js_function_definition.asp This article may be able to give you more information if you are interested.
@Theworm typeof is safe to use if you understand all its caveats.
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));

1 Comment

You can cheat Object.prototype.toString.call for a while now using Symbol.toStringTag. Just FYI.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.