Skip to main content

Posts

Showing posts with the label recursion

Recursion

Recursion is a technique used to solve computer problems by creating a function that calls itself until your program achieves the desired result. This tutorial will help you to learn about recursion and how it compares to the more common loop. What is recursion? Let's say you have a function that logs numbers 1 to 5. Here's how you write it using recursion: function log ( num ) { if ( num > 5 ) { return ; } console . log ( num ) ; log ( num + 1 ) ; } log ( 1 ) ; A recursive function example When you run the code above, the  log  function will simply call itself as long as the value of the  num  variable is smaller than  5 . A recursive function must have at least one condition where it will stop calling itself, or the function will call itself indefinitely until JavaScript throws an error. The condition that stops a recursive function from calling itself is known as  the base case . In the  log  function above, the base case is when  num  i