Peter
Peter

Reputation: 59

Is “function” a JavaScript type?

Is "function" a JavaScript type?

For example:

console.log(typeof alert) // returns function

Which suggests that "function" is indeed a type

However, in this ECMAscript documentation it says:

The ECMAScript language types are Undefined, Null, Boolean, String, Symbol, Number, BigInt, and Object”.

Could someone explain this to me?

Thanks in advance :)

Upvotes: 5

Views: 95

Answers (1)

Dai
Dai

Reputation: 155145

The behaviour of the typeof operator is documented in section 12.5.5, which has a table that answers your question.

It says (paraphrased):

  • Given the expression typeof val:
    • When val is an Object which implements the [[Call]] interface then typeof returns the string 'function'
    • When val is an Object which does not implement [[Call]] then typeof returns the string 'object'.

Thus, function is not a separate ECMAScript type, but is actually a specialization of the Object-type.


Do note that the information in the ECMAScript specification is very technical and narrowly specific and is intended primarily for implementors of ECMAScript engines and tooling - and while it is useful for developers using JS as a language, it is not intended to be beginner-friendly or serve as an introduction to the language - or to explain fundamentals.


The precise definition of a "function object" is explained in 6.1.7.2.

Upvotes: 9

Related Questions