+ 4

[JS] Why does this function always return 4?

function f(x){ if(x==4) return 4 else return f(x+1) } document.write(f(1))

7th Feb 2017, 11:05 PM
Pete Wright
Pete Wright - avatar
4 Respostas
+ 5
Because it loops in the same module, until it returns 4. f(1) -> f(2) f(2) -> f(3) f(3) -> f(4), break. returns 4.
7th Feb 2017, 11:10 PM
WALL_BUILDER
WALL_BUILDER - avatar
+ 2
in the below we passing the argument f(1) to f(x) its looping again and again in the same loop and adding +1 until it gets 4 then finally (4==4) true then it returns 4
8th Feb 2017, 5:11 AM
guru krishna
guru krishna - avatar
+ 1
Thanks WA, good explanation. I thought recursion is not possible in JS.
8th Feb 2017, 5:37 AM
Pete Wright
Pete Wright - avatar
+ 1
the function will loop until the condition will be true. x == 1 then f(x+1) x == 2 then f(x+1) and when x == 4 the code of if statement will execute.
4th Mar 2017, 11:02 PM
Amstrong Martins
Amstrong Martins - avatar