Kimchi Man
Kimchi Man

Reputation: 1171

Setting new Date() by number and string gives different result

I'm learning JavaScript and I found weird(?) behavior of JavaScript.

I create date objects by

var stack = new Date(1404187200000) // 07-01-2014
var overflow = new Date('07-01-2014')

And when I compare those two date objects

stack == overflow // returns false
stack.getTime() == overflow.getTime() // returns true

And I believe it's because they are not the same object. But I know that '==' is comparison of equality and '===' is comparison of identity - like this example:

var stack = 1;
var overflow = '1';
stack == overflow // returns true
stack === overflow // returns false

So, why does comparing new Date([NUMBER]) and new Date([STRING]) give a different result even though they are the same date?

Please enlighten me!

Upvotes: 0

Views: 147

Answers (3)

chiastic-security
chiastic-security

Reputation: 20520

You're misunderstanding the difference between == and ===. It's not that one does equality checking and one does reference checking.

For ===, the two operands have to have the same type. But for ==, type coercion is allowed before checking for equality.

In your case, the two objects are of the same type, so there's no difference between == and ===; but they are checking reference equality, not value. The right way to check for value equality with dates is as you're doing: check whether stack.getTime() == overflow.getTime().

You can also do +stack == +overflow, which will cast them both first, and then you'll get a value equality test.

Upvotes: 1

peter
peter

Reputation: 15129

This is a little bit more complicated. === checks the type while == tries to convert to a common type. That's why 1 == '1' is true but 1 === '1' is false, because in the first case '1' gets transformed to a number (AFAIR).

you can see the exact specification how that is handled here: http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3 - the interesting part for you in this case is 1. f.

Return true if x and y refer to the same object. Otherwise, return false.

Upvotes: 1

dhc
dhc

Reputation: 657

new Date returns an object. Each time you create it it will create a different object, so they're not equal. getTime returns a value (property) from the object-- this will be the same for both objects.

Upvotes: 1

Related Questions