-3

I need to make a fibonacci sequence and I found this code below here. When I try to understand all code I saw "(i <= 1) ? i : arr[i-2] + arr[i-1]", I thought that was an simple if else shortcut condition, and I try to replace by the extended way just to be sure (see the last code). But now the code didn't work...

Stackoverflow code:

function fib(n) {
  return new Array(n).fill(1).reduce((arr, _, i) => {
    arr.push((i <= 1) ? i : arr[i - 2] + arr[i - 1])
    return arr
  }, []);
}
console.log(fib(10))

My code with (extended if else):

function fib(n) {
  return new Array(n).fill(1).reduce((arr, _, i) => {
    arr.push(
      if (i <= 1) {
        i
      } else {
        arr[i - 2] + arr[i - 1]
      })
    return arr
  }, []);
}
console.log(fib(10))

Why my code is not equivalent to the code above?

  • 2
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator. You can't just drop an `if` in `.push()` – j08691 Aug 28 '21 at 18:30
  • 3
    Does this answer your question? [How do you use the ? : (conditional) operator in JavaScript?](https://stackoverflow.com/questions/6259982/how-do-you-use-the-conditional-operator-in-javascript) – TYeung Aug 28 '21 at 18:33
  • 1
    “*I thought that was an simple if else shortcut condition*” While this is kind of close to true, any old `if`/`else` is not a drop-in replacement for something that was originally written using the ternary operator `?` – esqew Aug 28 '21 at 18:33
  • Your code doesn’t work because it’s syntactically incorrect — simple as that. – Sebastian Simon Aug 28 '21 at 18:36

1 Answers1

0

Basically what @esqew said.

“I thought that was an simple if else shortcut condition” While this is kind of close to true, any old if/else is not a drop-in replacement for something that was originally written using the ternary operator ?

Replacing a Conditional Operator with an if statement directly will throw an error.

If you want to use if/else syntax inside a function parameter you could write the code as a function in the form of an IIFE.

(() => {
  if (i <= 1) {
    return i;
  } else {
    return arr[i - 2] + arr[i - 1];
  }
})();

Demo:

function fib(n) {
  return new Array(n).fill(1).reduce((arr, _, i) => {
    arr.push(
      (() => {
        if (i <= 1) {
          return i;
        } else {
          return arr[i - 2] + arr[i - 1];
        }
      })()
    );
    return arr;
  }, []);
}

console.log(fib(10));
lejlun
  • 4,140
  • 2
  • 15
  • 31