Recursive function

Description

A recursive function is a function which calls itself by name.

arguments.callee is a pointer to the function being executed and, as such, can be used to call the function recursively

Example


function factorial(num){// w w  w.  j av  a  2s .  c  om
   if (num <= 1){
      return 1;
   } else {
      return num * arguments.callee(num-1);
   }
}

Strict Mode

The value of arguments.callee is not accessible to a script running in strict mode. In strict mode, you can use named function expressions to define recursive functions


var factorial = (function f(num){
   if (num <= 1){/*from   w w  w  .  ja v  a2 s.  c  o m*/
      return 1;
   } else {
      return num * f(num-1);
   }
});




















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions