Date Object Type

I just read this article about W3Schools about type conversion in JS. It stands there:

There are 3 types of objects:

  • An object
  • the date
  • Array

This confused me because, as far as I know, there is no difference between Date objects and any other object ( typeof (new Date()) returns "object" ). At first, I thought it was special because it contains native code, but there are dozens of functions with native code.

Is this article incorrect? Or can someone tell me why the Date object is so unusual that it is considered a separate type of object?

+5
source share
2 answers

Lemm will tell you one thing. Articles at W3Schools are certainly out of date, so you should not rely on this. Yes, when you give this in the console:

 typeof (new Date()) 

The above code returns object , because JavaScript has only a few primitive types:

You can check if the date object is in use or not:

 (new Date()) instanceof Date 

The above code will return true . This is the right way to check if a particular variable is an instance of a particular type.

+9
source

You can check an object as an instance of a certain type, also by checking if it has a method specific to the object type in question:

 if (myobject.hasOwnProperty("getUTCMilliseconds")) { // myobject is a Date... 

The same method can help you identify arrays in Javascript:
check

 typeof(myobject) 

gives an "object" and not an "array" if myobject is really an array, so I use

 if (myobject.hasOwnProperty("slice")) { // we are dealing with an array here ... 
+1
source

Source: https://habr.com/ru/post/1247851/


All Articles