Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

4. Function() > A Function Can Call Itself (Recursion)

A Function Can Call Itself (Recursion)

It’s perfectly legitimate for a function to call itself. In fact, this is often used in well-known coding patterns. In the code below, we kick off the countDownFrom function, which then calls itself via the function name countDownFrom. Essentially, this creates a loop that counts down from 5 to 0.

Live Code

<!DOCTYPE html><html lang="en"><body><script>

var countDownFrom = function countDownFrom(num) {
   console.log(num);
   num--; // change the parameter value
   if (num < 0){return false;} // if num < 0 return function with no recursion
   // could have also done arguments.callee(num) if it was an anonymous function
   countDownFrom(num);
};

countDownFrom(5); // kick off the function, which logs separately 5,4,3,2,1,0

</script></body></html>

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint