Recursion

Creator:
Eric
Description:
Learn to use recursion to make your scripts better and more elegant

What is Recursion?

Recursion is an alternate method of performing something instead of iteratively. Iteration is the standard method of looping with something like while, or for, I'm sure that all of you know the drill. What you do with recursion is have a function call itself with a modified argument.

So How Does It Work?

One of the more common ways to demonstrate that is with a factorial, which is exactly what I'm going to do. As you know, a factorial is a number times all the whole numbers between it and 0. Lets go over the iterative method:

function factorial(x) {
    var work = x;
    while(x > 1) // Note that this is only this way because
    { // 1 * x = x, so there is no need to multiply by it
        work *= (--x);
    }
    return work;
}

As you can tell, this is probably the standard, normal way of doing it. But we can use recursion to make this code better:

function factorial(x) {
    if(x > 2) return x * factorial(x-1);
    return 1;
}

You see how a function can use itself to further perform its own duties? Its quite a useful method, and works rather well. From this you may be thinking that this is only useful for math and things like that, but once again this can be used for anything.

A DOM Example

Recursion can be used to perform the task of finding the exact pixel location of an object on the screen. Here is the code:

function getPosX(elem) {
    if(elem) return elem.offsetLeft + getPosX(elem.offsetParent);
    return 0;
}
function getPosY(elem) {
    if(elem) return elem.offsetTop + getPosX(elem.offsetParent);
    return 0;
}

Comments

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <b> <u> <i> <hr> <img src <url=
  • Lines and paragraphs break automatically.

More information about formatting options