Tony Stark Tony Stark - 1 year ago 87
Javascript Question

Confusion in regards to JavaScript data type and types of objects

I saw the following statements at W3school.

enter image description here

I came from a beginner java background, so the data types and types of objects in javascript is confusing me quite a bit. I have a few questions which I hope someone could kindly help me to answer.

  1. what does "object" data type consist of?

  2. What is the difference between data type "object" and types of objects "Object"?

  3. when I tried to find out the data type of "null" by typing
    typeof null
    , my IDE tells me that it is of type "object", not of type "null", which is what I expected.

Answer Source

typeof will always returns the primitive type. ('string', 'number', 'object', etc.).

An object is a primitive type structure, an unordered list of primitive data types stored as a series of name-value pairs.

Object is the constructor of an object primitive.

var test = {};
console.log(typeof test);             // object
console.log(test instanceof object)   // false
console.log(test instanceof Object)   // true

According to this, to check for a Date or an Array, using typeof will returns object:

typeof [];           // object
typeof new Date();   // object

To test if the object is actually a Date or an Array, you can use instanceof:

[] instanceof Array;          // true
new Date() instanceof Date;   // true

Regarding the typeof null, it's a bug in ECMAScript according to the MDN and should be null. The bug is detailed in this answer. A fix has been proposed via an opt-in, unfortunately the change was rejected due to code using this specific 'bug' to test for null.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download