+ 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))
4 ответов
+ 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.
+ 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
+ 1
Thanks WA, good explanation. I thought recursion is not possible in JS.
+ 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.