Skip to content Skip to sidebar Skip to footer

Confusion In Regards To Javascript Data Type And Types Of Objects

I saw the following statements at W3school. 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

Solution 1:

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);             // objectconsole.log(test instanceofobject)   // falseconsole.log(test instanceofObject)   // true

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

typeof [];           // objecttypeofnewDate();   // object

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

[] instanceofArray;          // truenewDate() instanceofDate;   // 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.

Solution 2:

W3Schools (not to be mistaken with W3C (World Wide Web Consortium)) often contains very inaccurate information. Discussion: Why not w3schools.com. Instead, use information provided by MDN for example.

Here is an article about data types in Javascript you will find useful: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures

To answer your questions:

Objects are just a collection of properties: combinations between a key (string, number, objects ...) and a value: other objects, functions, strings, numbers, ... Arrays (which has some custom things like indexation etc) and Dates are objects.

There is no such thing as object and Object.

The reason why typeof null returns object is because of old specs that were never changed. Why is typeof null “object”?

Post a Comment for "Confusion In Regards To Javascript Data Type And Types Of Objects"