0

I am writing a React Native application. At one point I have an if statement that should fire if two parts of the state are equal. In the case I am testing, the two parts seem to be equal, yet the comparison operator continues to return false. See console logs below:

enter image description here

Please note that I also separately logged the types of the two state objects as well as the types of the values associated with each key and those appear the same as well. What is going on here?

223seneca
  • 1,136
  • 3
  • 19
  • 47
  • 1
    You'll have to compare the properties by yourself as object comparaison doesn't exist in javascript: `this.state.mapviewPolygon[0].coordinates.latitude === this.state.markerMoving.latitude && this.state.mapviewPolygon[0].coordinates.longitude === this.state.markerMoving.longitude` – ibrahim mahrir Aug 21 '18 at 20:00
  • 1
    ... could use some caching too: `var a = this.state.mapviewPolygon[0].coordinates` and `var b = this.state.markerMoving` then `a.latitude === a.latitude && b.longitude === b.longitude` – ibrahim mahrir Aug 21 '18 at 20:02
  • I'll give that a shot. Interestingly, if I compare one of the objects to itself, I get `true`. I'm guessing something different is happening under the hood in that case? – 223seneca Aug 21 '18 at 20:17
  • For what it's worth, while I now agree that this question has been asked before, it was not apparent to me at the outset since there was a possibility that React or React Native, rather than Javascript, was the culprit. – 223seneca Aug 21 '18 at 20:20
  • 1
    @ 223seneca that's because objects are just references (pointers) to the actual data stored in memory. In your case the two object are pointers referenceing different data in memory. The data may look the same but it actuall two different locations (if you change one the other is unaffected, thus different). So `this.state.mapviewPolygon[0].coordinates` contains an adress and `this.state.markerMoving` contains another. When you compare them, you are comparing the adresses. Since they are different, the result is `false`. – ibrahim mahrir Aug 21 '18 at 20:22
  • 1
    ... The primitive values (strings, numbers, booleans, ...) however behave differently. When you compare two variables that are holding a primitive value, the actual data is compared. – ibrahim mahrir Aug 21 '18 at 20:23
  • 1
    Thanks, that is super clear and helpful! Not to mention totally lacking in condescension, which can be a real problem here sometimes. More users need to write comments like these. – 223seneca Aug 21 '18 at 20:23
  • You're very welcome! I'm glad I could help! – ibrahim mahrir Aug 21 '18 at 20:27

0 Answers0