Wednesday, May 14, 2008

Recursive Functions in JavaScript

posted by Jonah Dempcy

Recursive functions are functions which conditionally call themselves. A common use for recursive functions is anywhere you need to iterate on data, where you would normally use a for() or while() loop.

I can't say that I've used much recursion in production code, but it's a fun topic to write about, as there are plenty of fun uses of recursion to explore.

Let's start with a basic use of recursion, and replace a for() loop with a recursive function. In this case, we'll implement a simple function to reverse a string, first using iteration and then recursion.

// Iterative
function reverseString(str) {
    var rev = new String();
    for (var i = str.length - 1; i >= 0; i--) {
        rev += str[i];
    }
    return rev;
}

console.log(reverseString('test')); // Logs 'tset'
// Recursive
function reverseString(str) {
    var firstLetter = str.charAt(0);

    function iterate(str) {
        if (str.charAt(str.length-1) != firstLetter) {
            var charToReverse = str.charAt(str.length-1);
            str.charAt(str.length-1) = '';
            return iterate(charToReverse + str);
        }
    }
    return iterate(str);
}

console.log(reverseString('test')); // Logs 'tset'

1 Comments:

Blogger Lowell Kirsh said...

Why do you use new String() instead of ""?

September 2, 2008 at 1:18 AM  

Post a Comment

Subscribe to Post Comments [Atom]

<< Home