0

I want to be able to pass this function either a number to return as a factorial or a number and an id for an existing element on the page, so that it can return the number as text inside my specified element. Here is my code:

function factorial(num,id){
    var f=1
    for (var i=2; i<=num; i++) {
        f*=i;
    }
    if (!id) {
        return f;
    }
    else if (id) 
        var msg= document.getElementById(id);
        return {
        msg.textContent = num + "! =  " + output;
        };
    }
}

factorial(5,"message");
2
  • What is output? Should be f, isn't it? Commented Jul 2, 2014 at 14:06
  • 1
    why not return num + "! = " + output; where does output come from ? Commented Jul 2, 2014 at 14:09

1 Answer 1

1

Set the element if passed then return unconditionally:

function factorial(num, id){
    var f = 1;
    for (var i=2; i<=num; i++) {
        f *= i;
    }

    if (id) {
        document.getElementById(id).textContent = num + "! =  " + f;
    }

    return f;
 }

alert(factorial(5));

alert(factorial(5,"message"));
Sign up to request clarification or add additional context in comments.

3 Comments

Ahh I see what I was doing wrong. Plus I had used output without defining it. This works better.
Also for IE7/8 you need .innerText rather than .textContent. In this case you can use .innerHTML which works in everything
Thank for the tip. I knew innerHTML was good all around but wasn't aware that ie 7/8 wouldn't work with .textContent. Thanks for the heads up!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.