- 1

How this code alert 1.

function func(n) { if(n<=1) { return 1; } else { return func(n-1); } } alert(func(4));

30th Jul 2017, 7:38 PM
Ahmed Awad
Ahmed Awad - avatar
3 Answers
+ 3
1st call: n = 4; if = false; else = true else returns func(4 - 1) // n = 3 2nd call by else: n = 3; if false; else = true else return func(3 - 1) // n = 2 3rd call by else: n = 2; if false; else true else return func(2 - 1) // n = 1 4th call by else: n = 1; if true; else = false if returns 1 // no more func() calls by else, code stops
30th Jul 2017, 7:49 PM
Benneth Yankey
Benneth Yankey - avatar
+ 7
Because you told it to do so ...return 1; if you say "return 100;" 100 will be the output. try this... var n; function func(n) { if(n<=1) { return n; } else { return func(n-1); } } alert(func(parseInt(prompt()))); with the above code, every input will give "1" since it returns the final value of n as @Ben Bright explained
30th Jul 2017, 8:52 PM
Nomeh Uchenna Gabriel
Nomeh Uchenna Gabriel - avatar
+ 2
thanks brother for clear this misunderstand.
30th Jul 2017, 8:06 PM
Ahmed Awad
Ahmed Awad - avatar