12 Days of Posts: Day 1 – Functions can return functions

I am attempting to do something a little different. Right now everywhere you go there is something related to Christmas. This inspired me to challenge myself to write 12 short posts before Christmas. Here is the first.

Functions can return functions

In JavaScript functions are first class objects. For our purposes here that means that functions can be returned from other functions, used as parameters for other functions, and the value stored in a variable.

This means we can take a simple function like this:

function add(x, y){
  return x + y;
}

This is a completely arbitrary function but we will build another function to return this one.

function returnAFunction(){
  console.log('In returnAFunction');
  return add;
}

This just has a console call to let us know when we execute it and then it returns our add function.

Here are some things that we can do with this now:

var returnedAdd = returnAFunction();
//console logs In returnAFunction
returnedAdd(1,2)
//the output would be 3
returnAFunction()(2,2)
//console logs In returnAFunction
//the output would be 4

First we capture the returned function as returnedAdd. We can then use that as if it was our add function. Next we execute returnAFunction and then immediately execute the returned function. This demonstrates the first class nature of functions. Functions are not some special type that must be defined first and then executed. We can pass functions around just like we would any other object.

Why would we do this? The post tomorrow will build on this idea and answer why would we do this.


Enjoyed the article?

Then I guarantee that you will find my video series useful and enjoyable. The course focuses on taking someone completely new to Node.js and giving them a great foundation to start building real applications. The course is named The Complete Guide to Node.js.

Feel comfortable with Node.js and want to build web applications? Then you will find my other video series useful. It is named Building Complex Express Sites with Redis and Socket.io

I also have a book! It covers Node.js, Express, Passport, Socket.IO, Redis, RabbitMQ, React, Backbone, Grunt, and Ansible. All in one book! It is called Building Scalable Apps with Redis and Node.js.

Receive tips on Node.js, Python, and more