JavaScript

Calling a function that has no name

You can make use of recursion easily in JavaScript. Let's try it with factorials:

function factorial(num){
    if (num < 0) {
        return -1;
    } else if (num == 0) {
        return 1;
    }

    return (num * factorial(num - 1));
}

If all the conditions fail, the function calls itself one more time with the argument decremented by one. This is easy but there are cases where the function is an anonymous function. Something like this:

data.map(function(num){
    if (num < 0) {
        return -1;
    } else if (num == 0) {
        return 1;
    }

    return (num * ??????(num - 1));
});

How do we refer call a function that has no name? When a function is called, JavaScript injects an array like variable that holds all the parameters passed to the function and some extra properties. The arguments variable.

This variable holds a reference to the function being called. arguments.callee(). So here is how it will work.

data.map(function(num){
    if (num < 0) {
        return -1;
    } else if (num == 0) {
        return 1;
    }
    return (num * arguments.callee(num - 1));
});

Warning!

Argument.callee is being deprecated. Meaning, you would have to move on from this trick eventually.

JavaScript accepts passing a named function in the same manner you pass an anonymous function:

data.map(function factorial(num){
    if (num < 0) {
        return -1;
    } else if (num == 0) {
        return 1;
    }
    return (num * factorial(num - 1));
});

The alternative would be to define the function first.


Comments

There are no comments added yet.

Let's hear your thoughts

For my eyes only