You-Dont-Need-Lodash-Underscore icon indicating copy to clipboard operation
You-Dont-Need-Lodash-Underscore copied to clipboard

Why don't you use `instanceof` for `isDate`?

Open munierujp opened this issue 3 years ago • 4 comments

Here is example code:

// Lodash
console.log(_.isDate(new Date()));
// output: true

// Native
console.log(new Date() instanceof Date);
// output: true

munierujp avatar Apr 22 '22 11:04 munierujp

I think you can check that:

https://stackoverflow.com/a/643827

"you can use the instanceof operator, i.e. But it will return true for invalid dates too, e.g. new Date('random_string') is also instance of Date"

Its-Just-Nans avatar Jul 05 '22 12:07 Its-Just-Nans

Lodash also returns true for invalid dates such as _.isDate("random_string").

gilly3 avatar Apr 26 '23 19:04 gilly3

Also jest can mess up the instanceof functionality.

Uzlopak avatar Oct 17 '23 09:10 Uzlopak

Lodash also returns true for invalid dates such as _.isDate("random_string").

You should have said

import _ from 'lodash'

console.log(_.isDate("random_string")) // false
console.log(_.isDate(new Date("random_string"))) // true, it's a Date, but invalid

Note: if you want a code that check, you can check as writed on the stackoverflow link with something like

Object.prototype.toString.call(a) === '[object Date]' && !isNaN(a)
import _ from 'lodash'


const test = (a)=>{
    console.log(
    _.isDate(a),
    a instanceof Date,
    Object.prototype.toString.call(a) === '[object Date]',
    Object.prototype.toString.call(a) === '[object Date]' && !isNaN(a)
  )
}

test("random_string")
// false false false false
test(new Date('random_string'))
// false false false false
test(new Date())
// false false false true

playground: https://playcode.io/lodash

Its-Just-Nans avatar Oct 17 '23 21:10 Its-Just-Nans