Skip to content

Instantly share code, notes, and snippets.

@AlexJWayne
Last active November 17, 2015 18:38
Show Gist options
  • Save AlexJWayne/6b1d2b4e1097f66e3970 to your computer and use it in GitHub Desktop.
Save AlexJWayne/6b1d2b4e1097f66e3970 to your computer and use it in GitHub Desktop.

if is not an expression, meaning it does not return a value. A ternary is an expression, meaning it does return a value. This allows you to use it on the right hand side of an assignment operator.

So when assigning things, this is needlessly verbose

var someEl = document.getElementById('some-element');
if (isCool) {
  someEl.innerText = 'totally cool';
} else {
  someEl.innerText = 'NOT COOL YO';
}

when you could have just:

var someEl = document.getElementById('some-element');
someEl.innerText = isCool ? 'totally cool' : 'NOT COOL YO';

Like any programming construct, you can use it badly. A common mistake is putting complex logic in that bitch:

var foo = obj.foo && obj.bar.baz === 'whatever' || obj.wtf > obj.bbq ? 'herp' : 'derp'

And if you start nesting them, I kill you:

// Syntactically valid but FUCK YOU
var foo = isBar ? isFoo ? 'A' : 'B' : barType == 'iron' ? 'C' : 'D'

TL:DR; the ternary is nice when your condition and your branches are simple, and you want a return value from it. But it's easy to abuse, and if your logic gets more complex refactor your code and change that to a proper multiline if statement for better readability. But when used wisely, they can enhance readability by keeping code more concise.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment