Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Why don't you use instanceof for isDate? #340

Open
munierujp opened this issue Apr 22, 2022 · 4 comments
Open

Why don't you use instanceof for isDate? #340

munierujp opened this issue Apr 22, 2022 · 4 comments

Comments

@munierujp
Copy link

Here is example code:

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

// Native
console.log(new Date() instanceof Date);
// output: true
@munierujp munierujp changed the title Why don't you use instanceof for isDate? Why don't you use instanceof for isDate? Apr 22, 2022
@Its-Just-Nans
Copy link

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"

@gilly3
Copy link
Contributor

gilly3 commented Apr 26, 2023

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

@Uzlopak
Copy link
Contributor

Uzlopak commented Oct 17, 2023

Also jest can mess up the instanceof functionality.

@Its-Just-Nans
Copy link

Its-Just-Nans commented Oct 17, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants