0

here is my code,

var a = new Date(1); // it returns Thu Jan 01 1970 05:30:00 GMT +0530 (India Standard Time)
var b = new Date(1); // it returns Thu Jan 01 1970 05:30:00 GMT +0530 (India Standard Time)

if(a != b)
   debugger; 

when i run that code the condition was hit(succeed).. how it is possible. because both a and b date time values are same.

Akbar Basha
  • 1,168
  • 1
  • 16
  • 38
  • 1
    `a` and `b` are `Date` objects. And objects are compared by reference. You may want to compare `a.getTime() != b.getTime()` – Oriol Jan 29 '15 at 16:53

1 Answers1

0

In your example, a and b are two different objects of the same type, potentially with the same value, but the equality operators recognize that they are different instances and as such are not considered equal. The spec covers exactly how that works.

If you want to compare them, you need to compare the values within the objects. Calling getTime() on both will give you numbers, which can be safely compared. There's also a chance that the two objects don't have the same value (allocated just as the clock ticks), so getTime() may not always be true.

var a = new Date();
var b = new Date();

console.log(a == b); // Always false, a and b are different instances
console.log(a.getTime() == b.getTime()); // Usually true, since getTime returns a number
ssube
  • 47,010
  • 7
  • 103
  • 140