Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialYao Tung Ooi
13,744 PointsI'm a bit confused about calling the game() function when we are still inside the game() function... How does that work?
I'm a bit confused about calling the game() function when we are still inside the game() function... How does that work?
Will all the variables be reset again? As if we are calling it the first time?
1 Answer
Larry McGee
5,747 PointsWhen a function calls itself this is called "recursion". This technique is usually introduced at a more advanced stage of a programming class.
As to why he used recursion in this beginner level program, my guess would be that he is so use to using this technique that he didn't realize he used it until after recording the lesson.
When you make a recursive call the computer saves the current state (all variables and their values) of the current function call and then creates a new instance of the function and begins execution with it's own set of variables. When that instance completes execution the program returns to the point where the recursive call was made and continues execution with the previously saved state.
If you do a quick search for "how does recursion work" you will find several visual tutorials that explain the technique and how it works.