0

I am want to have function to computer factorial of integer numbers. I created function with loop under it and then call the function to pass the number and get the result. But it outcomes undefined, although all variables are declared properly.

<script>
   var userInput;
   var num;
   var i =1;
   var fact;
               
   function myFactor (num){
     
   fact = num * i;
   
    for (i; i <= num; i++) {
    fact = fact * i;
    
    return fact;
    }
   }
   
   
   var result = myFactor(fact);
   userInput = prompt("Enter Value:",""); 
   num = parseInt (userInput);   
   
   document.write(result);
</script>

There are many codes that achieve this but I want to learn that why my code does not work.

Maihan Nijat
  • 9,054
  • 11
  • 62
  • 110

2 Answers2

1

You forgot the closing brackets before and after returning and to call the function with the number given by the user and one iteration too many.

var userInput;
var num;
var i =1;
var fact;

function myFactor (num){    
  fact = num * i;
  for (i; i < num; i++) {
    fact = fact * i;
  }
  return fact
}

var result;
userInput = prompt("Enter Value:","");  
num = parseInt (userInput);         
result = myFactor(num);
document.write(result);

Should work now. BTW: the function computes a factorial, factoring is something different. Ow, too late again.

deamentiaemundi
  • 5,502
  • 2
  • 12
  • 20
  • It works. Just add ; for closing the return statement. – Maihan Nijat Oct 23 '15 at 01:07
  • 1
    @deamentiaemundi This is correct, but this function (as well as OP's) is not idempotent. You are modifying the global `i` from within the `myFactor` function, so calling `myFactor` multiple times in a row will produce incorrect results on subsequent calls. For clarity and correctness, I would declare and initialize both `i` and `fact` inside `myFactor`. – Igor Raush Oct 23 '15 at 01:09
  • You don't need to in ECMA-script. But you're right, of course, some see it as a better style to do so and it is sometimes difficult to tell where it is possible to drop and where not.. – deamentiaemundi Oct 23 '15 at 01:09
  • @IgorRaush I'm too slow for this world ;-) But I like to change only so much as needed in the OPs code not more. I think it is easier for them to tell which parts were broken. – deamentiaemundi Oct 23 '15 at 01:11
0

try:

var userInput;
var num;

var fact;

function myFactor(num) {

    var i = 1;
    fact = num * i;

    for (i; i <= num; i++) {
        fact = fact * i;

        return fact;
    }
}
userInput = prompt("Enter Value:", "");
num = parseInt(userInput);
var result = myFactor(num);

alert(result);
Barmar
  • 741,623
  • 53
  • 500
  • 612
Kevin Simple
  • 1,225
  • 10
  • 22