-
-
Save getify/5a20a5334e7e6ca557a1a51637e6f5f7 to your computer and use it in GitHub Desktop.
Nested ternary: good vs bad
This file contains hidden or 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 hidden or 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; | |
} |
Both of them are the root of bad readability.
Nope, only the first one is bad, but it's bad both ways ;-)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Both of them are the root of bad readability.