Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding the typeof operator in Javascript

I came across the following table which states the internal [[Class]] property of an object and its corresponding value that the typeof operator returns.

Value               Class      Type
-------------------------------------
"foo"               String     string
new String("foo")   String     object
1.2                 Number     number
new Number(1.2)     Number     object
true                Boolean    boolean
new Boolean(true)   Boolean    object
new Date()          Date       object
new Error()         Error      object
[1,2,3]             Array      object
new Array(1, 2, 3)  Array      object
new Function("")    Function   function
/abc/g              RegExp     object (function in Nitro/V8)
new RegExp("meow")  RegExp     object (function in Nitro/V8)
{}                  Object     object
new Object()        Object     object

One thing to note here is the typeof correctly returns the primitive data types associated in Javascript.

However, it returns an object type for an array which inherits from the Array.prototype, but returns a function type for a function that is inheriting from the Function.prototype.

Given everything is an object in Javascript (including arrays, functions & primitive data type objects), I find this behaviour of the typeof operator very inconsistent.

Can someone throw some light on how the typeof operator works in reality?

like image 699
nashcheez Avatar asked Feb 16 '17 12:02

nashcheez


1 Answers

This is slightly odd, idiosyncratic Javascript behaviour. It's inherited from the earliest days of Javascript and probably would not be written in such a way today.

Nonetheless, we are where we are with Javascript, so we have to deal with it!

The thing is that values in Javascript are either objects or they are primitives. This is a design decision. They cannot be anything else. The types of primitives are:

  • strings
  • numbers
  • booleans
  • symbols (from ES2015)
  • the special value undefined
  • the special value null (for which typeof also returns object)

Anything and everything else is an object. This is by design. Arrays are objects, so typeof returns object, as does every other object that is not callable (i.e. a function). See the spec for typeof.

The better question is to ask why you want to test if something is an array. You probably don't need to, especially as array-like objects such as NodeLists are not arrays but are like them in many ways.

The best solution in most cases is to call Array.from on the value supplied: then you know that it is an array.

like image 110
lonesomeday Avatar answered Nov 01 '22 12:11

lonesomeday