JavaScript's First Class Functions

First Class Functions

What does it mean for for functions to be first class? Do they get a complementary salad? Comfortable seats? Actual leg room for reasonably sized legs?

Alas, JavaScript functions still have to ride in coach with the rest of us, but they do come standard with special features.

In JavaScript you can take a function as a parameter or return it as a value.

check this out:

function call_function_n_times(some_function, n) {  
    for (i = 0; i < n; i++) {
        some_function()
    }
}

function say_hello() {  
    console.log('Yo yo!')
}

call_function_n_times(say_hello, 3)  

If you run that bit of code you should see the following:

Yo yo!  
Yo yo!  
Yo yo!  

call_function_n_times is a function that takes another function and a number as arguments, then calls first parameter the number of times specified in the second parameter.

Why this is useful may not be immediately obvious. Trust me, I think you'll begin to see the super-cool-itude of this in future posts.

Another example:

function make_power_function(power) {  
    function power_function(number) {
        return Math.pow(number, power)
    }
    return power_function
}

var squared = make_power_function(2)  
var cubed = make_power_function(3)

console.log('3 squared is', squared(3))  
console.log('2 cubed is', cubed(2))  

If you run that bit of code you should get:

3 squared is 9  
2 cubed is 8  

call_function_n_times takes a function as a parameter and make_power_function returns a function.

And that's what it means for a function to be first class.

Looking for a software developer?