Functions as First Class Citizens in Javascript

July 31st, 2015

In Javascript we are lucky. We get the ability to pass functions around, our functions can even return functions. And this is great. As a teacher, one thing I find is that this idea confuses people learning the language. Functions are a bit of an abstract concept. So I wanted to go over a few things we can do with functions in regards to passing them around and playing with them!

This is focused for people just learning the language. Yet if you have been writing JS for a while, you might learn a thing of two as well!

First Class Citizens?!

In programming languages, when you are able to pass, return and assign a type, that type is considered to be a first class citizen [source]. This is one reason Javascript is becoming a popular destination for functional programming. Since we are able to create functions that can accept functions as well as return functions. This allows us to create Higher Order Functions. Higher Order Functions are functions that accept a function, and/or return a function [source].

Types inside of Javascript are first class citizens, we are able to assign, pass and return all the different types in JS.

Assigning functions.

In Javascript we can assign a function to a variable in many ways.

Using var

var myFunction = function() {
    //...function body here 
};

A common pattern is to define a function using the var keyword to store a function in a variable. We use an anonymous function here, but you could also use a named function if you desired.

var myFunction = function functionName() {
    //...function body here 
};

This will give you a reference to the function inside of the function, useful for recursion. It allows you to call the function inside of itself!

var myFunction = function functionName(n) {
    if(n < 10)   {
        n++;
        ...some code
        functionName(n);
    }
};

Methods

Assigning a method in Javascript is super easy as well. Similar to how we can assign a function to a variable we can assign a function as a value to a key in an object.

var warrior = {
    hp: 100,
    strength: 20,
    attack: function(target) {
        target.hp -= this.strength;
    }
}

One thing to remember here is that when we create a function like:

var add = function(a,b) {
    return a + b;
}

The value stored inside the add variable is a function, so we can pass that value around without calling the function.

var newAdd = add;
newAdd(2,3) //5

Passing functions.

Since functions are first class citizens in Javascript, we are able to pass them. A common use case as a beginner might be something like this. Lets assume we have some sort of analytics we need to preform on various types of events.

You could do something like this.

$('form').on('submit',function() {
    //perform some analytics.
});

$('a[href$=".pdf"]').on('click', function() {
    //perform same analytics.
});

There is a bit of repetition here, and we want to prevent that as much as possible. With the ability to pass functions, we can reduce repetition, and pass one function to be run when the user interacts with those elements.

function analyticsHandler(e) {
    ...//perform some analytics.
}

$('form').on('submit',analyticsHandler);

$('a[href$=".pdf"]').on('click',analyticsHandler);

This way, jQuery will just see the function as a value and call it when the event is fired. Which, if you think about it, is all you are doing when you provide a callback function.

$('a').on('click', function() {
    //...
});

Internally jQuery will call the callback function when it sees that the <a> tag is clicked. In our analyticsHandler example, we are simply storing the function in an easy to use variable for later use. And it is helping us keep things DRY.

Returning functions.

Something else we will look at is returning functions from functions. This can be a powerful concept if you master it, and this is a key concept when it comes to functional programming.

Consider the process of writing a gulp file. We use the require statement from Node.js to get scripts into our file.

var cssNext = require('gulp-cssnext');

When you write module in Node you are able to return multiple things, however it is fairly common to simply return a function. That is why when you require something, especially a gulp plug in, you have to able to call that function later, the value returned from the require call is a function.

Here is an example from the gulp-cssnext plug-in.

module.exports = function(options) {
  return through.obj(transform(options))
}

This is a line from index.js in gulp-cssnext. They use module.exports to return a function, which itself returns the results of a function call. This way we can use the returned function in our gulp files like this.

gulp.task('css',function() {
    gulp.src('*.css')
        .pipe(cssnext())
        .pipe(dist.);
});

A common pattern you will see when working with a Node app, especially an express app is a line similar to this.

var app = require('express')();

In express you need to require it and then execute the function to create your express application. It is very common to shorten this process down to one line.

Another place you will see this is when using postcss. In postcss you require all of your packs in the postcss module, like this:


postcss([ require('cssnext')(), require('cssnano')() ])

Note the cssnext referred to here is not the gulp-cssnext plugin, but to original cssnext package. In this implementation the cssnext package returns a function, that when run, sets itself up to work with postcss.

Partial application

Another common use for returning a function, is for partial application. Partial application is used to set up a function that returns a function. Calling the first function saves the first argument or arguments that were passed in. What?! Let’s look at a simple example.

Example:

function add(a) {
    return function(b) {
        return a + b;
    }   
}

This function takes an a parameter and returns a function that will then take the second parameter b. The a is remembered inside of the second function because of the closure that the returned function created. Lets look at an example of how to use it.

var add5 = add(5);

The value now saved in add5 is the function. Inside of that function it references a and it remembers that because when it was created, a was available to it.

function(b) {
    return a + b;
}

What way we can go ahead and call it with new values that will always add 5 to the new value.

add5(5); // 10
add5(8); // 13

For a more in depth article on partial application and currying check out this article by Dave Atchley and this one by Eric Elliott.

Javascript is a powerful fun language to learn and work with, and with functions as first class citizens we are very lucky! I hope this helped with your understanding of functions, learning a language like Javascript can be draughting to a beginner, but with practice you can start to chip away at it!


Warning: count(): Parameter must be an array or an object that implements Countable in /home/ryanch6/public_html/wp-includes/class-wp-comment-query.php on line 405