isDate and isNumber in the Popular Javascript Utility Library

Easy to misuse it without proper knowledge of what it is

Kharis Khasburrahman
Jan 14 · 2 min read

You might frequently use a javascript utility library for your application. Either to speed up your development process or just simply want some utility function that is proven working and have been tested. Some popular utility libraries that we know are lodash and underscore.

Have you ever use the utility library to validate whether a variable is a valid number? Valid means that the value will not cause an error or will not return an unexpected result, like NaN. If you have lodash or underscore dependency, you might be tempted to use that isNumber function. It seems to do just that, right?

Let’s look at both lodash and underscore implementation for isNumber function.

Both of the popular libraries have a similar implementation. They will compare the variable Javascript class name type with the [object Number] string. That applies to not only Number type but also to other types such as Date, function, etc.

You might think it’s fine, but do you aware that NaN is also a Number in Javascript? NaN in javascript is a Number that represents the value: Not-A-Number. Kinda confusing right? You can check it out yourself in the javascript console.
// -> [object Number]

So, using isNumber method isn’t really the correct way for the above use case. We need another validation, that is checking if the number is not NaN . We will end up with something like this.

const isValidNumber = _.isNumber(obj) && !isNaN(obj)

So how about the isDate function? What can potentially cause an issue?

Try to initialize invalid Date object, Like new Date("31/1/2019") or new Date("test123") . The resulting value will still be a Date object but it will be an invalid Date object. That will likely cause your Date related logic flawed. Therefore we should add another step for validating Date object, maybe this is sufficient:

const isValidDate = _.isDate(obj) && !isNaN(obj.getTime()) 



Easy read, easy understanding. A good writing is a writing that can be understood in easy ways

Kharis Khasburrahman

Written by

Software Engineer



Easy read, easy understanding. A good writing is a writing that can be understood in easy ways

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade