Maihan Nijat
Maihan Nijat

Reputation: 9355

Javascript function to compute factorial of integer number

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.

Upvotes: 0

Views: 1057

Answers (2)

deamentiaemundi
deamentiaemundi

Reputation: 5525

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.

Upvotes: 1

Kevin Simple
Kevin Simple

Reputation: 1213

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);

Upvotes: 0

Related Questions