I've seen this idiom show up in various open-source projects:
it instanceof Array || typeof it == "array"
I know the second half cannot be true in ECMAScript 5 (or 6), but is/was there ever an implementation that would return "array" from typeof? Or is this a case of bogus defensive programming?
The typeof operator returns "object" for objects, arrays, and null. The typeof operator does not return "object" for functions.
Summary. JavaScript doesn't support functions that return multiple values. However, you can wrap multiple values into an array or an object and return the array or the object. Use destructuring assignment syntax to unpack values from the array, or properties from objects.
This because in javascript all derived data type is always a type object. Included functions and array. In case you need to check if it's an array you can use isArray method of Array. and the result will be the same as the previous one.
Arrays are Objects The typeof operator in JavaScript returns "object" for arrays.
No, at least since the first version of ECMAScript.
ECMAScript 1 (June 1997)
11.4.3 - The
typeof
operatorThe production UnaryExpression :
typeof
UnaryExpression is evaluated as follows:
- Evaluate UnaryExpression.
- If Type(Result(1)) is Reference and GetBase(Result(1)) is null, return
"undefined"
.- Call GetValue(Result(1)).
Return a string determined by Type(Result(3)) according to the following table:
- Undefined:
"undefined"
- Null:
"object"
- Boolean:
"boolean"
- Number:
"number"
- String:
"string"
- Object (native and doesn’t implement [[Call]]):
"object"
- Object (native and implements [[Call]]):
"function"
- Object (host): Implementation-dependent
ECMAScript 2 (August 1998)
No changes.
ECMAScript 3 (December 1999)
No relevant changes.
11.4.3 - The
typeof
operatorThe production UnaryExpression :
typeof
UnaryExpression is evaluated as follows:
- Evaluate UnaryExpression.
- If Type(Result(1)) is not Reference, go to step 4.
- If GetBase(Result(1)) is null, return
"undefined"
.- Call GetValue(Result(1)).
Return a string determined by Type(Result(4)) according to the following table:
- Undefined:
"undefined"
- Null:
"object"
- Boolean:
"boolean"
- Number:
"number"
- String:
"string"
- Object (native and doesn’t implement [[Call]]):
"object"
- Object (native and implements [[Call]]):
"function"
- Object (host): Implementation-dependent
ECMAScript 4
This spec was abandoned.
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