YourJS.nativeType()

Last updated on Monday, September 9th, 2019 @ 10:44AM.

Using typeof can be very useful in certain cases to find the type of a primitive, but how can you find the type of an object such as an array or a date? You can use YourJS.nativeType().

For example, let's say that you want to find the type of all of the values in an array:

var array = [
  1,
  'B',
  null,
  /4|5/,
  undefined,
  new Date(),
  [1, 2, 3, 4],
  function(){},
  { name: 'John Smith' }
];

If we want to use typeof on primitives such as booleans, numbers or strings we will not have any issue. On the other hand, if we want to even be able to determine is something is a RegExp, an Array, or a Date object, typeof is not the way to go. Instead we can use YourJS's nativeType() function. The following will show the difference between using typeof and YourJS.nativeType():

As you can see in the example above, the typeof works well on 1, 'B', false, undefined, function(){} and the object literal. Unfortunately, it doesn't work well with null regular expressions, dates, or arrays. On the other hand, YourJS.nativeType() works well with them all. This is because it leverages JavaScript's Object.prototype.toString() function to get the native type name. That means that even if the value being tested is an object form of a primitive its type will still be determined by YourJS.nativeType() but not by typeof:

How Does YourJS.nativeType()?

It is really simple!

  1. Pass the value into Object.prototype.toString.call().
  2. Remove the first 8 characters and the last character of the return value.
  3. VoilĂ , you are done!

Final Words

It isn't always necessary to use YourJS.nativeType() but there are plenty of times when it comes in handy. Feel free to download it along with any other YourJS functions you may want. Happy coding! 😎