Skip to content

Instantly share code, notes, and snippets.

@kevboutin
Created October 17, 2023 15:29
Show Gist options
  • Save kevboutin/e69e4bd75453a353bd74a146fab26bf7 to your computer and use it in GitHub Desktop.
Save kevboutin/e69e4bd75453a353bd74a146fab26bf7 to your computer and use it in GitHub Desktop.
Conditional Flow Control
/* Instead of using this:
const getNumWord = (num) => {
if (num === 1) {
return 'one';
} else if (num === 2) {
return 'two';
} else if (num === 3) {
return 'three';
} else if (num === 4) {
return 'four';
} else return 'unknown';
};
console.log(getNumWord(1)); // one
console.log(getNumWord(3)); // three
console.log(getNumWord(7)); // unknown
Or even this:
const getNumWord = (num) => {
switch (num) {
case 1:
return 'one';
case 2:
return 'two';
case 3:
return 'three';
case 4:
return 'four';
default:
return 'unknown';
}
};
console.log(getNumWord(1)); // one
console.log(getNumWord(3)); // three
console.log(getNumWord(7)); // unknown
This is best:
*/
const getNumWord = (num) =>
num === 1
? 'one'
: num === 2
? 'two'
: num === 3
? 'three'
: num === 4
? 'four'
: 'unknown';
console.log(getNumWord(1)); // one
console.log(getNumWord(3)); // three
console.log(getNumWord(7)); // unknown
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment