+ 3
can someone explain me this
function fact(a){ if(a<=0||a==1){ return 1 } else{ return a*fact(a-1)} } alert(fact(4))
6 Answers
+ 2
alert(fact(4)) will alert (show in an alert box) the result of calling the function âfactâ with the argument 4 .
The function first checks if a is smaller than or equal to 0, or if a is equal to 1. Since a=4, this is not the case.
it goes to the else statement which returns 4*fact(3).
by repeating this logic you get that fact(3) returns 3*fact(2).
fact(2) is 2*fact(1).
for fact(1), the if statement becomes true, because a===1 is true.
The overall return value is thus
fact(4)=4*fact(3)=4*3*fact(2)=4*3*2*fact(1)=4*3*2*1=24
the expression 4*3*2*1 is also known as the factorial of 4, and is denoted by 4!
+ 4
do some examples
1 returns 1
0 returns 1
2 returns 2*1
3 returns 3*2*1
....
+ 1
thanks alot John Doe
+ 1
Read about call stacks and recursion.
A stack is an abstract data type that follows the principle of LIFO i.e last in first out.
1 function fact(a){
2 if(a==1)
3 return 1
4 else{
5 let x=fact(a-1)
6 return a*x
7 }
8 }
9
10 console.log(fact(5));
So on running the program the call stack has no call in it yet but as it gets to line 10 the function fact is called with an argument of 5
fact(5) get pushed into the call stack
The program moves to line 1 and the if condition is checked it returns false then the else condition gets executed.
On getting to line 5 it calls the function fact with 4 which is a-1 and so on it continues till it gets to fact(1) then the if condition is checked which returns 1 and terminates the recursion.
fact(5) calls fact(4) calls fact(3) calls fact(2) calls fact(1)
with fact(1) returns 1 to fact(2) and fact(2) returns 2*1 to fact(3) and fact(3) returns 3*2*1 to fact(4) and fact(4) returns 4*3*2*1 to fact(5) and fact(5) returns 5*4*3*2*1 which is 120
0
Thanks Awogbami Victor