+ 1

Why? 4

What is the output of this code? function f(x) { if(x==4) return 4; else return f(x+1); } alert(f(1)); answer 4

25th Aug 2018, 3:01 AM
ŠŠ»Š¼Š°Ń‚ ŠŠ¹Ń‚Š±Š°ŠµŠ²
ŠŠ»Š¼Š°Ń‚ ŠŠ¹Ń‚Š±Š°ŠµŠ² - avatar
2 Answers
+ 5
That is a recursive function that takes a number as an argument. The else statement is the recursive case while the if statement is the base case. For every recursive call, the argument passed is increased by 1 until it reaches 4 and that makes the base case true, thus returning the value 4.
25th Aug 2018, 4:40 AM
Jonathan Pizarra (JS Challenger)
Jonathan Pizarra (JS Challenger) - avatar
+ 3
Based on the only constant return in the function, 4 is the only feasable and possible answer.
25th Aug 2018, 4:00 AM
Nicolas Burnett
Nicolas Burnett - avatar