Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is “function” a JavaScript type?

Tags:

javascript

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 :)

like image 452
Peter Avatar asked Oct 11 '20 09:10

Peter


1 Answers

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.

like image 88
Dai Avatar answered Sep 30 '22 11:09

Dai