+ 1
help me understand this function
function f(x) { if (x == 4) { return 4 } else { return f(x + 1) } } console.log(f(1)) //4
2 Answers
+ 7
This function will always return 4 provided the given parameter is <= 4
The function checks at the start if the given value is 4, and if so then it returns 4.
But if the given value is not 4, then the function again call itself with value + 1.
This means the function will recursively call itself and at last will return 4.
But note that if you passed any value more than 4, then the function will call itself infinity times. Because in that case value will never be equal to 4. And ultimately your program may crash, due to stack overflow.
+ 1
Its an very unuseful function that would return 4 but, on some (eg. many) inputs, "returns" an error because too recursion function calls