DEV Community

Pete Corey
Pete Corey

Posted on • Originally published at petecorey.com on

Elixir Style Conditions in Javascript

Elixir has a useful control flow structure called cond that lets you branch on arbitrary conditions. Unlike the more common switch control structure (case in Elixir), cond doesn’t match against a predetermined value. Instead, it evaluates each condition, in order, looking for the first one that evaluates to a truthy value (not nil or false).


numbers = [1, 2, 3]
result = cond do
  4 in numbers ->
    :four
  6 == Enum.sum(numbers) ->
    :sum
  true ->
    :default
end

This is all probably old hat to you.

As I mentioned, cond can be an incredibly useful control structure, and there are times when I’ve missed it while working in languages like Javascript that only have switch expressions.

A traditional Javascript implementation of the above (with a little help from Lodash) would look something like this:


let numbers = [1, 2, 3];
if (_.includes(numbers, 4)) {
  var result = "four";
} else if (6 === _.sum(numbers)) {
  var result = "sum";
} else {
  var result = "default";
}

However, I recently stumbled upon a trick that lets you implement a switch statement in Javascript that behaves very similarly to a cond expression in Elixir. The key is to switch on the value of true. The case expressions that evaluate to true will match, and their corresponding statements will be evaluated in order.


let numbers = [1, 2, 3];
switch (true) {
  case _.includes(numbers, 4):
    var result = "four";
    break;
  case 6 === _.sum(numbers):
    var result = "sum";
    break;
  default:
    var result = "default";
    break;
}

Whether or not this is any more useful or readable than a series of if/else blocks is debatable. That said, this is definitely an interesting example of perspective shifting and seeing old code in a new light. Hopefully you find it as interesting as I do.

Top comments (0)