Created
July 5, 2017 15:37
-
-
Save bmdoherty/f106a2474d84c1f9b6b8fff31db6b51d to your computer and use it in GitHub Desktop.
object comparison
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// object test for equality fails as object need to be pointing to same reference in memory | |
// primitives like strings and numbers are compared by their value | |
function greetFailing(person) { | |
if (person == { name: 'amy' }) { | |
return 'hey amy' | |
} else { | |
return 'hey arnold' | |
} | |
} | |
// JSON.stringify() method converts a JavaScript value to a JSON string, for comparison | |
// or use library for object compare, ie lodash | |
function greetWorking(person) { | |
if (JSON.stringify(person) == JSON.stringify({ name: 'amy' })) { | |
return 'hey amy' | |
} else { | |
return 'hey arnold' | |
} | |
} | |
greetFailing({ name: 'amy' }); | |
greetWorking({ name: 'amy' }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment