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

2
  • I think you want the class name of the object. A good answer : stackoverflow.com/questions/332422/… Commented Nov 12, 2013 at 12:20
  • if you want it the fast way if (prevDate instanceof Date) ... might be a solution. Commented Nov 12, 2013 at 12:29

4 Answers 4

1

You can get it by following:

var prevDate=new Date(2000, 2, 2)
console.log(Object.prototype.toString.call(prevDate));
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

one line function :

console.log( function(prevDate) {
  return ({}).toString.call(prevDate).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
});

Comments

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]"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.