Anonymous And Fat Arrow Functions

Remember this function?

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

In another post, we named another function, say_hello, and passed it as an argument to call_function_n_times.

Here's another way to pass a function to call_function_n_times:

call_function_n_times(  
    function () {
        console.log('this is being printed from an anonymous function')
    },
    4)

If you run this code, you should see:

this is being printed from an anonymous function  
this is being printed from an anonymous function  
this is being printed from an anonymous function  
this is being printed from an anonymous function  

Here we're giving call_function_n_times an anonymous function as an argument. An anonymous function is just a function without a name. You can stick it anywhere you would put a regular function, including as an argument to another function.

In ES2015 (a more up-to-date version of JavaScript that runs on Node) there's a shorthand way of writing anonymous functions:

call_function_n_times(() => { console.log('this is being printed from fat arrow function') }, 4)  

Their official name is arrow-functions, but they're often called fat-arrow functions since they use an equals sign instead of a dash.

They're pretty slick right? In fact, if your function is a one-liner, you can omit the curly braces.

call_function_n_times(() => console.log('this is being printed from fat arrow function'), 4)  

Another cool feature of fat-arrow functions is that if the function is only one line, their return value is whatever the value of that one line is:

var add = (num1, num2) => num1 + num2

console.log(add(1,2))  

This should print 3. Look Ma! No return statement!

O.K. check this out:

var power_function_maker = (power) => (number) => Math.pow(number, power)

var power_4 = power_function_maker(4)

console.log(power_4(2))  

This prints 16.

What's going on here? power_function_maker is a fat-arrow function with one line, another fat arrow function. This second inner function, what power_function_maker returns, also has only one line, a function call that returns the result of number to the power of power. This is what the inner function returns.

I love fat-arrow functions and will be using them from here on out. :)

Looking for a software developer?