News for hackers. Stuff that matters.

Bite-size coding challenge: implement if/else in JavaScript without `if` or `?:`

Here's a bit of Friday fun for you: your mission, should you choose to accept it, is to implement if/then logic in JavaScript without using `if` or the ternary operator `?:`.

Implement a function with the following signature:

```` function ifThenElse(cond, trueFn, falseFn) { } ````

If `cond` is truthy, execute `trueFn`, otherwise execute `falseFn`. `ifThenElse` should not have a return value.

Here's a gist that contains a very tiny test harness: https://gist.github.com/shinypb/befb5363395c754758b157b850cf747a

Put your implementations into your own gist and then reply to this thread.

I'm curious to see what sort of horrible atrocities you can all come up with. :) Happy hacking!

PS: Here are my two ideas:

https://gist.github.com/shinypb/85d6dd19e712f4d7962bd4c0cb30dfec

https://gist.github.com/shinypb/78dd126d946bec6cc77245d40d0748cb

( 2 comments | 4 points | on HN )
Re:Bite-size coding challenge: implement if/else in JavaScri... by elliotbnvl on Friday January 10, 2020 @03:25PM (#22015101)

  function ifThenElse(cond, trueFn, falseFn) {
      ({ true: () => trueFn(), false: () => falseFn() })[cond]();
  }
Re:Bite-size coding challenge: implement if/else in JavaScri... by Someone on Friday January 10, 2020 @04:11PM (#22015583)

  function ifThenElse(cond, trueFn, falseFn) {
    cond && trueFn();
    cond || falseFn();
  }