Jorge Bermúdez Jorge Bermúdez - 3 years ago 214
Javascript Question

Fibonacci Recursive Function in js how it works?

I found this function in another question but i dont really understand how it works.

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

console.log(fibonacci(4));
//fibonacci secuence

brk brk
Answer Source

function fibonacci(n) {} is one of the way of writing function in javascript. This is called function Declaration.One of the advantage of declaring in this way is you can call the same function when there is recursion,mean in the function body you can call the function again using the name that is being done here fibonacci(n - 1) + fibonacci(n - 2); where fibonacci is the function name.

The following is a syntax for ternary operator

condition ? expr1 : expr2

Which mean is if condition is evaluated to true then expr1 will be evaluated & if false expr2 will be evaluated.

The ternary operator can be nested(not recommended as it increase function complexity)

n < 1 ? 0 : n <= 2 ? 1 : fibonacci(n - 1) + fibonacci(n - 2);

The above expression is nested ternary operator ,for simplicity of understanding it can be divided in two part ,part-1 n < 1 ? 0 ,part-2 : n <= 2 ? 1 : fibonacci(n - 1) + fibonacci(n - 2).Part-2 is nested ternary operation.

According to part-1 if n is less than 1, set it to 0 else(second part) if n is less than equal to 2 set it to 1, else again recall the same function by using the name of the function(fibonacci)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download