I'm just writing a very simple function in javascript to calculate a factorial. I understand that in javascript you can assign a function to a variable.
So I have tried this on an online compiler (https://repl.it/languages/javascript) and this is what my code looks like
var mynum = prompt("Enter a number", "<enter a number>");
var answer;
if (isNaN(mynum)){
console.log(mynum +" is not a number");
}
else{
console.log("You entered "+mynum);
answer = function (mynum){
var i = mynum-1;
var temp = mynum;
while(i>0){
temp = temp*i;
i--;
}
return temp;
};
console.log("the factorial of "+mynum+" is "+answer);
}
But when I run this the output keeps including the whole function as "answer"
You entered 23
the factorial of 23 is function (mynum) {var _loopStart = Date.now(),_loopIt = 0;
var i = mynum - 1;
var temp = mynum;setTimeout(function () {_loopStart = Infinity;});
while (i > 0) {if (++_loopIt > 5000 && Date.now() - _loopStart > 150) throw new RangeError("Potential infinite loop. You can disable this from settings.");
temp = temp * i;
i--;
}
return temp;
}
However i don't have this issue when i create the function and then call it separately (something like answer = function(mynum).
Can anyone please let me know why this is happening?
Thanks!