1

When comparing two strings, like so:

'03-15-2019' < '03-16-2019'

I get a value of true, which is what I expect.

I'm curious to learn a little more about how this works though. Is this doing a comparison of two dates, or is there some other comparison going on that I don't quite see?

5
  • 1
    string comparison Commented Mar 14, 2019 at 17:07
  • 4
    It's just comparing strings, not dates. Change the year of the second date to 2015. The comparison result will be the same. Commented Mar 14, 2019 at 17:07
  • 2
    It's a pure string comparison. '5'.charCodeAt() is lower than '6'.charCodeAt() Commented Mar 14, 2019 at 17:08
  • 2
    Those are not Date strings as far as JavaScript is concerned, just a jumble of alpha-numeric characters, so there is no chance of any "type-coercion" which is the proper name for what you are suggesting. Commented Mar 14, 2019 at 17:12
  • Obligatory XKCD: xkcd.com/1179 Commented Mar 14, 2019 at 17:20

2 Answers 2

1

String comparison happens character by character

console.log('aaaa' < 'b')
console.log('aa' < 'ab')
console.log('ab' < 'aa')

'03-15-2019' < '03-16-2019' This is just string comparison not date comparison, if you want to compare dates you need to change it to date Object and than compare

console.log(new Date('03/15/2019') < new Date('03/16/2019'))

Sign up to request clarification or add additional context in comments.

Comments

0

Date strings are just strings so they obey javascript string comparison rules.

console.log('04-13-2019' < '04-15-2019') #true

But be careful here because if you rely on this comparison because if the two strings are not of the same length, it will result in unexpected behaviors like this:

console.log('ab' < 'b') #true

If you want to compare dates, you would better rely on Date object or use moment js

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.