Skip to content

Instantly share code, notes, and snippets.

@emjayess
Created December 1, 2010 17:34
Show Gist options
  • Save emjayess/723868 to your computer and use it in GitHub Desktop.
Save emjayess/723868 to your computer and use it in GitHub Desktop.
javascript's flexible ternary
// the agility of javascript's ternary operation...
// lots of folks don't seem aware of the subsequent assignments available
function ternary(a,b) {
var c,d,tis='';
c = (d = a==b) ? tis='tis true' : tis='tis false';
return [c,d,tis];
}
console.log(ternary(true,true));
console.log(ternary(true,false));
console.log(ternary(false,false));
@emjayess
Copy link
Author

I hereby acknowledge that with this example, I have violated style guidelines within Crockford's "The Elements of JavaScript Style, Part Two: Idioms" (http://javascript.crockford.com/style2.html)...

Use the ?: operator to select one of two values.

and

Do not use the ?: operator to select one of two actions.

@emjayess
Copy link
Author

here's another ternary gem that also demonstrates usage of the comma-as-operator...
lives ? (lives--, go()) : (gameOver(), exit());

via http://javascriptweblog.wordpress.com/2011/04/04/the-javascript-comma-operator/

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