Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save bga/1993712 to your computer and use it in GitHub Desktop.

Select an option

Save bga/1993712 to your computer and use it in GitHub Desktop.
[fun] various forms of ternary operator in JavaScript
// add your variants of
a ? b : c
// in comments :)
// a is boolean
// b and c - any type
// lazy evaluation isnt important
@zachleat

zachleat commented Mar 9, 2012

Copy link
Copy Markdown

I believe

[c, b][a]

should be

[c, b][+a]

Edit: Damn you mathias! :)

@vrs

vrs commented Mar 12, 2012

Copy link
Copy Markdown

@jneira I love that lambda calculus inspired version. How about this? (Credits to you, this is just sugar)

var lambdas = {
  true: function(x) {return function(y) {return x}},
  false: function(x) {return function(y) {return y}},
  ifthenelse: function (x) { return function(y) { return function(z) {return (x(y))(z)}}}
}
function ternary (a,b,c) {
  return lambdas.ifthenelse(lambdas[!!a])(function(_) {return b})(function(_){return c})()
}
console.log(ternary("a","b","c"))
// b
console.log(ternary(false,"b","c"))
//c

@jneira

jneira commented Mar 13, 2012

Copy link
Copy Markdown

better, but credits to Alonzo Church!, we are simple mortals

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