0

For example I have a some code:

({}).toString.call(new Date()); // "[object Date]"

anybody knows, another methods how to check type? (I wanna to receive only date type without object)

  • 1
    did you tried `typeof`? – Luis felipe De jesus Munoz Aug 28 '18 at 20:46
  • @LuisfelipeDejesusMunoz , typeof return only object, I need a `date` –  Aug 28 '18 at 20:48
  • 2
    If you already know it is an `object` type, you can use `instanceof` or check the constructor function. – user268396 Aug 28 '18 at 20:51
  • @user268396 you are not right, `instanceof` we can use if we know type, in this case is better to use `variable.constructor.name` – аlex Aug 28 '18 at 21:09
  • Keep in mind that JavaScript is very dynamic, so any solution you find is probably not 100% reliable, meaning that only because something returns a specific value it may not be what you expect. Case in point: `({}).toString.call({[Symbol.toStringTag]: 'Date'})`. – Felix Kling Aug 28 '18 at 22:29
  • Please note that the name of an object's constructor is a totally different concept from [*Type*](http://ecma-international.org/ecma-262/9.0/#sec-ecmascript-data-types-and-values). Values have a Type (number, string, object, etc.), all objects are type object, unless they're also functions, in which case they are type function. – RobG Aug 28 '18 at 22:49

1 Answers1

2

The best way to check types the way you are asking to is using the method you already posted. You can make it a little bit easier though.

function type(value) {
  const tag = Object.prototype.toString.call(value);
  return tag.slice(8, -1);
}

console.log(type(new Date()));
console.log(type(5));
console.log(type(function() {}));
snek
  • 1,980
  • 1
  • 15
  • 29
  • This is a good way to go about it, but the function should not be called "Type". By convention, function names starting with a capital letter denote constructors, and [*Type*](http://ecma-international.org/ecma-262/9.0/#sec-ecmascript-data-types-and-values) is a totally different concept to constructor name (which is more akin to "class", but that name should probably be avoided too). – RobG Aug 28 '18 at 22:52