0

I'm comparing two dates in objA and objB, and they are not equal as the following console output shows.
Can't understand why..

objA[keysA[i]]
Sun Sep 25 2016 00:00:00 GMT+0900 (KST)
objB[keysA[i]]
Sun Sep 25 2016 00:00:00 GMT+0900 (KST)
typeof objA[keysA[i]]
"object"
typeof objB[keysA[i]]
"object"
objA[keysA[i]] !== objB[keysA[i]]
true
1
  • because dates are an object you can not compare them like that ... try objA[keysA[i]]+0 !== objB[keysA[i]]+0 which coerces the dates to a Number Commented Oct 26, 2016 at 3:48

2 Answers 2

1

In JavaScript you compare objects by reference.

let a = {};
let b = {};
let c = a;

a == b //false
a == c //true

A simple way of comparing objects is to convert them to a string and compare the string. You can use Date.prototype.toString to compare Date objects like this

objA[keysA[i]].toString() !== objB[keysA[i]]].toString() //false
Sign up to request clarification or add additional context in comments.

Comments

1

You'll need to stringify the dates & compare them that way. For example:

var date1 = new Date(); 
var date2 = new Date();

console.log (date1==date2); // This will print false

But if we stringify the dates and compare them that way this will become true, like so:

console.log (date1.toString() === date2.toString())

2 Comments

date1+0 === date2+0 as well - and accounts for millisecond differences
Yep. @JaromandaX - If you were to do date1+0 === date2+0 | It'd = true as you said.

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.