Skip to content

Instantly share code, notes, and snippets.

@bmdoherty
Created July 5, 2017 15:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmdoherty/f106a2474d84c1f9b6b8fff31db6b51d to your computer and use it in GitHub Desktop.
Save bmdoherty/f106a2474d84c1f9b6b8fff31db6b51d to your computer and use it in GitHub Desktop.
object comparison
// 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