Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Has JavaScript typeof ever returned "array"?

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?

like image 342
Peter Dillinger Avatar asked May 15 '15 16:05

Peter Dillinger


People also ask

Does typeof return array?

The typeof operator returns "object" for objects, arrays, and null. The typeof operator does not return "object" for functions.

Can JavaScript return an array?

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.

Why typeof array is object in JavaScript?

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.

What is the typeof an array in JavaScript?

Arrays are Objects The typeof operator in JavaScript returns "object" for arrays.


1 Answers

No, at least since the first version of ECMAScript.

ECMAScript 1 (June 1997)

11.4.3 - The typeof operator

The production UnaryExpression : typeof UnaryExpression is evaluated as follows:

  1. Evaluate UnaryExpression.
  2. If Type(Result(1)) is Reference and GetBase(Result(1)) is null, return "undefined".
  3. Call GetValue(Result(1)).
  4. 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 operator

The production UnaryExpression : typeof UnaryExpression is evaluated as follows:

  1. Evaluate UnaryExpression.
  2. If Type(Result(1)) is not Reference, go to step 4.
  3. If GetBase(Result(1)) is null, return "undefined".
  4. Call GetValue(Result(1)).
  5. 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.

like image 151
Oriol Avatar answered Sep 29 '22 23:09

Oriol