0

I want to check the type of an variable in my method as below

var prevDate=new Date(2000, 2, 2)
console.log(typeof prevDate);

now the it returns "object" as type, but it is the type of date. how can i get the type of prevDate using "typeOf" and dont want to use the jQuery.type(prevDate), as it takes more time to execute.

Thanks In advance

user2918741
  • 87
  • 1
  • 10
  • I think you want the class name of the object. A good answer : http://stackoverflow.com/questions/332422/how-do-i-get-the-name-of-an-objects-type-in-javascript – Rémi Benoit Nov 12 '13 at 12:20
  • if you want it the fast way `if (prevDate instanceof Date) ...` might be a solution. – hgoebl Nov 12 '13 at 12:29

4 Answers4

1

You can get it by following:

var prevDate=new Date(2000, 2, 2)
console.log(Object.prototype.toString.call(prevDate));
Nikhil N
  • 4,507
  • 1
  • 35
  • 53
1

The typeof works sufficiently well with primitive values (except null). But it says nothing about object types. Fortunately, there is a hidden [[Class]] property in all JavaScript native objects. It equals “Array” for arrays, “Date” for dates etc. This property is not accessible directly, but toString, borrowed from native Object returns it with a small wrapping, for example:

var toClass = {}.toString

alert( toClass.call( [1,2] ) ) // [object Array]
alert( toClass.call( new Date ) ) // [object Date]

You can read more here

fortegente
  • 1,361
  • 2
  • 11
  • 22
0

one line function :

console.log( function(prevDate) {
  return ({}).toString.call(prevDate).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
});
Nadeem_MK
  • 7,533
  • 7
  • 50
  • 61
0

Object.toString returns a string representing the object.

var prevDate=new Date(2000, 2, 2);
console.log(Object.prototype.toString.call(prevDate));

Output: "[object Date]"
Prateek
  • 6,785
  • 2
  • 24
  • 37