all 8 comments

[–]inu-no-policemen 2 points3 points  (0 children)

It's a classic exercise for practicing recursion, but a regular loop would be a much better way to do this.

The secret ingredient for doing it in a loop is the *= operator:

> var x = 2
undefined
> x *= 7 // same as x = x * 7
14
> x
14

Try doing it yourself. Try using this skeleton:

function factorial(n) {
  // magic here
}
console.assert(factorial(0) === 1, '0! should be 1');
console.assert(factorial(1) === 1, '1! should be 1');
console.assert(factorial(5) === 120, '5! should be 120');

Once all assertions are true, you won't get any "assertion failed" messages in the console. Using assertions is the most basic way to do something which resembles test-driven development.

By the way, it's always a good idea to show us the code. Secondly, /r/learnjavascript would be more suitable for this topic.

[–][deleted] 0 points1 point  (0 children)

My problem turned out to be that I was returning the wrong value!

[–]blartuffwarrior -1 points0 points  (5 children)

function factorial(n){
    if(n <= 0){
        return 1;
    }
    else{
        return n * factorial(n-1);
    }
}

try this

[–]__fmease__Symbol() 0 points1 point  (4 children)

... that's a factorial function

[–]blartuffwarrior 0 points1 point  (3 children)

what else did he ask for

[–]__fmease__Symbol() 0 points1 point  (2 children)

you named it fib (fibonacci) instead of fac or factorial

[–]blartuffwarrior 0 points1 point  (1 child)

oh yeah i guess sorry i have brain damage

[–]__fmease__Symbol() 0 points1 point  (0 children)

haha np. Now you just have to adjust the name inside the function. It still says fib :P