In his Eloquent Javascript, Haverbeke claims that (page 16):
"In a JavaScript system, most of this data is neatly separated into things called values. Every value has a type, which determines the kind of role it can play. There are six basic types of values: numbers, strings, Booleans, objects, functions, and undefined values."
But Crockford in Javascript: The Good Parts says:
"The simple types of JavaScript are numbers, strings, booleans (true and false), null, and undefined. All other values are objects. Numbers, strings, and booleans are object-like in that they have methods, but they are immutable. Objects in JavaScript are mutable keyed collections. In JavaScript, arrays are objects, functions are objects, regular expressions are objects, and, of course, objects are objects."
Now, at least under V8 I get this:
> typeof function(){};
'function'
> typeof {};
'object'
I don't understand if object is a type and function is an object or if function and object are both types. I guess I'm missing the distinction between primitive types and other kind of types (composite types?).
In JavaScript functions are first-class objects - a function is a regular object of type function .
Object is a function, but not every object is a function.
A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output.
function is a StreamBase data type and a reserved keyword. Use a constructor for the function data type to create a custom expression language function whose components are built-in functions, math operators, and even other functions.
They're a type of object.
The typeof
is "function"
:
typeof (function() {}) === "function" // true
The internal [[Class]]
is [object Function]
:
({}).toString.call(function() {}) === "[object Function]" // true
They're an instance of the Function
constructor prototype:
(function(){}) instanceof Function // true
They're an instance of the Object
constructor prototype:
(function(){}) instanceof Object // true
You need to be careful when talking about types in javascript. Values have a Type, which may be one of the following:
Perversely, the value returned by the typeof
operator is not the Type, it's a string that is the same as the Type for most values, but is different for:
[[Call]]
returns function, even though its Type is ObjectSo the bottom line is that the Type of a function is Object, but typeof someFn
returns function
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With