Reputation: 59
When I try this function it console logs as -3, but when I work it out on my own, it seems like it would return 12. Why is this?
function func(x) {
if (x <= 0) {
return x;
}
return func(x - 5);
}
console.log(func(17));
Upvotes: 0
Views: 85
Reputation: 779
As the other answers have said, the reason it returns -3
is because of recursion and because you've called the function from within itself.
However, I'd like to also add the code which I think you were trying to write if you were expecting the output to be 12
:
function func(x) {
if (x <= 0) {
return x;
}
return x - 5;
}
console.log(func(17)); // <---12
You don't need to reference func
when you return x
.
Upvotes: 0
Reputation: 616
When a method calls itself until it meets specific criteria.In this example, the func()
method will continue to call itself, passing in x-5
as the parameter until it's less than 0, at which point it'll return the current value of x
. So the callstack would look something like this:
func(17)
is (17 <= 0)? No
func(17 - 5)
is(12 <= 0)? No
func(12 - 5)
is(7 <= 0)? No
func(7 - 5)
is(2 <= 0)? No
func(2 - 5)
is(-3 <= 0) Yes!
return -3
Upvotes: 1
Reputation: 88
because on the return you call it again
function func(x) { <-- x=17
if (x <= 0) {
return x;
}
return func(x - 5); <---x=12 so now you call the func with 12
}
console.log(func(17));
step 2
function func(x) { <-- x=12
if (x <= 0) {
return x;
}
return func(x - 5); <---x=7 you call with 7
}
console.log(func(17));
step 3
function func(x) { <-- x=7
if (x <= 0) {
return x;
}
return func(x - 5); <---x=2 you call with 2
}
console.log(func(17));
step 4
function func(x) { <-- x=2
if (x <= 0) {
return x;
}
return func(x - 5); <---x=-3 you call with -3
}
console.log(func(17));
final step
function func(x) { <-- x=-3
if (x <= 0) {
return x; <--- now you print the result
}
return func(x - 5);
}
console.log(func(17));
Edit:
Recursive functions are functions that call themselves untill a break condition its true, in your example that break condition is x its equal (=) or less(<) than 0, and then print the result.
with 17 the first number you get sustracting 5 that return true con break condition is -3
Upvotes: 4
Reputation: 497
That is right you should get -3. Your recursive function says keep subtracting x by 5 until x is less than or equal to 0. So the first iteration would be 12 then 7 then 2 then finally -3 which meets the condition of being less than or equal to 0 and it then returns x
Upvotes: 1
Reputation: 3596
You call it once, then it keeps calling itself (at the second return) as long as the value is above 0. So it keeps going until the value is below 0, then it returns the final result.
Upvotes: 1