-
-
Save getify/5a20a5334e7e6ca557a1a51637e6f5f7 to your computer and use it in GitHub Desktop.
Nested ternary: good vs bad
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
var data = x ? y ? z ? z : y : x : 0; | |
// I call this the "if..if" pattern, and it's BAD. It means: | |
var data; | |
if (x) { | |
if (y) { | |
if (z) { | |
data = z; | |
} | |
else { | |
data = y; | |
} | |
} | |
else data = x; | |
} | |
else { | |
data = 0; | |
} |
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
var data = x ? x : y ? y : z ? z : 0; | |
// can be formatted as: | |
var data = | |
x ? x : | |
y ? y : | |
z ? z : | |
0; | |
// I call this the "if..else if" pattern, and it's much BETTER. It means: | |
var data; | |
if (x) { | |
data = x; | |
} | |
else if (y) { | |
data = y; | |
} | |
else if (z) { | |
data = z; | |
} | |
else { | |
data = 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nope, only the first one is bad, but it's bad both ways ;-)