Trying to understand recursion

Hello everyone,

I have a question about how recursion works for this code I managed to make. It’s supposed to take a number as a parameter and add up all subsequent numbers starting from 1.
For example addUp(3) would be (1 + 2 + 3) and should give us 6.

function addUp(num) {
	var first = 1
	if (num === 1) {
		return first;
	}
	else {
		return num += addUp(num-1)
	}
}

This is what I have so far, and the code seems to work. But, for a situation like addUp(3), once I get back down to addUp(1) what happens there?
To my understanding the code will calculate it starting from 3, so it will execute it as
3 + 2 + addUp(1)
I already have an if statement for num === 1 though. So I’m a little confused. Can anyone help me out with this?

Thanks,
Peter

addUp(3) is adding 3 to the output of addUp(2), but before having that output, also addUp(2) need to execute, and addUp(2) add 2 to the output of addUp(1)

addUp(1) returns 1
so now that this is finished, also addUp(2) can finish, and add 2 to 1 (so 3)
and now finally also addUp(3) can have an output, with 3 + addUp(2) becoming 3 + 3, so the output is 6

2 Likes

Hey @peter.yj.cha!

I am also a beginner and recursion is definitely one of those tricky topics that takes a second to sink in. Here are some resources that helped me further grasp the concept.

https://www.freecodecamp.org/news/understanding-recursion-in-javascript/

Yeah I thought so. It seemed sort of similar to a for loop.
You have been very helpful,
thanks a ton,
Peter

Hello!

I will check out this video, hope it helps!

Much appreciated,
Peter