Skip to content

Instantly share code, notes, and snippets.

@getify
Last active September 17, 2020 22:45
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save getify/5a20a5334e7e6ca557a1a51637e6f5f7 to your computer and use it in GitHub Desktop.
Save getify/5a20a5334e7e6ca557a1a51637e6f5f7 to your computer and use it in GitHub Desktop.
Nested ternary: good vs bad
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;
}
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;
}
@amerllica
Copy link

Both of them are the root of bad readability.

@immaterial
Copy link

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