JavaScript
Conditional Ternary Operator

by Benny Neugebauer

function fib(n) {
  return (n <= 1) ? n : fib(n - 1) + fib(n - 2);
}

function fib(n) {
  if (n <= 1) {
    return n;
  } else {
    return fib(n - 1) + fib(n - 2);
  }
}

Second one is cleaner.. even though I would remove the else part :)

Lipis

I would actually opt for the former, especially if we're in ES6 land and (presumably) using an arrow function.

That said, for more complicated cases I might break the ternary statement over multiple lines, ? and : at the start of the line, indented.

Jim O'Brien

Another good approach from the WeAllJS community:


const fib = n => n <= 1

  ? n

  : fib(n - 1) + fib(n - 2)

Benny Neugebauer

Sign in to comment!