I just read this article on W3Schools about type conversion in JS. There stands:
There are 3 types of objects:
- Object
- Date
- Array
This confused me because to my knowledge there isn't any difference between Date
objects and any other object (typeof (new Date())
returns "object"
). First I thought that it's special because it contains native code, but there are dozens of functions with native code.
Is this article wrong? Or could anybody tell my why the Date
object is so extraordinary that it's considered a separate type of object?
The Date object is an inbuilt datatype of JavaScript language. It is used to work with dates and times. The Date object is created by using new keyword, i.e. new Date(). The Date object can be used date and time in terms of millisecond precision within 100 million days before or after 1/1/1970.
You can use the ! isNaN() function to check whether a date is valid. If x is a Date, isNaN(x) is equivalent to Number.
You can create a Date object using the Date() constructor of java. util. Date constructor as shown in the following example. The object created using this constructor represents the current time.
Lemme tell you a basic thing. The articles in W3Schools are definitely outdated so you must not rely on it. Yes, when you give this in console:
typeof (new Date())
The above code returns object
because the JavaScript has only a few primitive types:
You can check if it is a date
object or not using:
(new Date()) instanceof Date
The above code will return true
. This is the right way of checking if the particular variable is an instance of a particular type.
You might check an object for being an instance of a specific type also by verifying whether it has a method that is specific to the object type in question:
if (myobject.hasOwnProperty("getUTCMilliseconds")) {
// myobject is a Date...
The same technique may help you identifying arrays in Javascript:
checking
typeof(myobject)
yields "object"
, not "array"
if myobject
is really an array, so I use
if (myobject.hasOwnProperty("slice")) {
// we are dealing with an array here ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With