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)