DEV Community

Cover image for Determining real data types in Javascript using Object.prototype.toString
Sunil Chaudhary
Sunil Chaudhary

Posted on

Determining real data types in Javascript using Object.prototype.toString

Is there an alternative (and maybe better way) to determine data type of variables in javascript other than typeof? Turns out there is one.

Recently, I was looking at some code and found a different way some developers were using to determine the data types using Object.prototype.toString instead of typeof. On further exploration, I found that Object.prototype.toString gives much better results as compared to typeof and can be useful at a lot of places.

Let’s look at some of the results it gives:

Application

Though typeof works fine for most of the cases, toString will come in handy covering cases such as

  • we need to differentiate between various types in objects (such as arrays, null, object, date)
  • we need to get correct data type for primitive variables created using their respective object wrappers (e.g. new Number(10) is a number but typeof will give object)

Syntax

One can also write a wrapper around it or even modify the function prototype to remove the unnecessary characters in the output and get only datatypes

Pros vs Cons

  • It seems typeof is more compact than toString in its usage as well as the result it returns but toString is more accurate.
    • toString gives more accurate data types which are useful when differentiating between various types of objects (arrays, null, objects, date)
    • toString gives more accurate results in cases if someone has used object wrapper for primitive data types such as new Number/String.
  • toString function can be overriden but typeof can’t which seems the only major drawback.

You can read more about the mechanism and working of the function over here.

Overall, Object.prototype.toString is a pretty good method to determine the datatypes correctly in lot of cases.


Top comments (0)