Last active
January 2, 2018 11:11
-
-
Save bkinsey808/f4f0b222eb58387da2c281427a446e2e to your computer and use it in GitHub Desktop.
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
// suppose I have the following: | |
const a = expensiveFunction() ? 1 : 0 | |
const b = expensiveFunction() ? 10 : 0 | |
const c = expensiveFunction() ? 100 : 0 | |
// liberal let would let you refactor like this: | |
let a, b, c | |
if (expensiveFunction()) { | |
a = 1 | |
b = 10 | |
c = 100 | |
} | |
// whereas the optimized constantly const would look more verbose, like this: | |
const expensiveFunctionResult = expensiveFunction() | |
const a = expensiveFunctionResult ? 1 : 0 | |
const b = expensiveFunctionResult ? 10 : 0 | |
const c = expensiveFunctionResult ? 100 : 0 | |
// but if eliminating verbosity is your goal, there is another way: | |
const [a, b, c] = expensiveFunction() ? [1, 10, 100] : [0, 0, 0] | |
// or perhaps | |
const {a, b, c} = expensiveFunction() | |
? { a: 1, b: 10, c: 100} | |
: { a: 0, b: 0, c: 0} | |
// personally, I run into a case like this so infrequently, and in general I prefer ternary operator over if, | |
// so the constantly const workarounds are ok for me in this case and comes down to style preference. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment