+ 1
Who is help me explain it why is output 1
14 Respostas
+ 3
It Outputs one because the function is called over and over, until the n <= 1
When n <= 1, It returns 1
+ 2
Pls send the code of resulting in 3
+ 2
Тимур Завьялов you need to understand and look at your code carefully ,in the following code you just posted ,no call to function is being made again and again , function is simply called once with func(4) which checks if 4<=1 ,if yes return 1 else return n-1 which results in 3
as in the previous code you were calling function again and again by return func(n-1) instead of n-1 ,notice the difference now?
+ 2
Abhay, thank you, I understood, I don't understand what's difference between "return" and "return func". Now I got it :)
+ 2
Тимур Завьялов glad you got it ,your welcome!!✌️
+ 2
I was not able to comment yesterday, sorry
ANY WAY YOU GOT THE ANSWER
+ 2
Recursion could be tricky for someone who is trying it for first time.
Due to recursion your function func() is executing again and again.
let's break how your code is working.
when you call the statement:
alert(func(4))
the JS starts to executing your function.
func(4) return another function func(3),
func(3) return func(2)
func(2) return func(1)
and func(1) returns 1.
and this same procedure will go for all the functions return by the func(4) which means you will be getting 1 for each function func(1), func(2), func(3) and func(4).
but you are doing nothing with the return value, as a result you get only func(4) last return value as 1.
+ 2
Answer is right. Because, this function has ability to call itself over over until n <= 1. And that's why this function has a special name called "Recursive Function".
+ 1
Steve, why if you remove "func" of return it outputs 3?
+ 1
I don't understand what is the difference
+ 1
Steve, no big deal :)
+ 1
Vinay, thank you)
+ 1
The code is so designed that
1) if condition is true it would return 1
2) if condition is false it would call itself once again with (n-1).
So we have coded it in such a way that it has to decrement 'n' until it is =1.