Skip to content

Instantly share code, notes, and snippets.

@katepapineni
Last active August 5, 2020 03:20
Show Gist options
  • Save katepapineni/f69c232f66afc7102fc6fdf0ef240fc4 to your computer and use it in GitHub Desktop.
Save katepapineni/f69c232f66afc7102fc6fdf0ef240fc4 to your computer and use it in GitHub Desktop.
/* || operator vs. If */
const hero = { name: 'Wonder Woman', age: 0, address: null };
// As || operator
const getOrOperator = ({ name, age, address }) => (
address // hero.address is falsy
|| age // hero.age is falsy
|| name // hero.name is truthy so short-circuits and is returned
|| 'hero' // default
);
// As If statements
const getIf = ({ name, age, address }) => {
if (address) {
return address;
}
if (age) {
return age;
}
if (name) {
return name; // hero.name is truthy it is returned
}
return 'hero';
};
console.log(getOrOperator(hero)); // => Wonder Woman
console.log(getIf(hero)); // => Wonder Woman
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment