Callback!
Using callbacks in functional Javascript
I’ve spent much of the last week trying to solidify my understanding of Javascript fundamentals. One of the major functionalities that is tremendously useful in web development is the use of callback functions.
In Javascript, functions are considered “first-class” objects, meaning they are treated just the same as any other object. One can assign a function to a variable, treat a function as a parameter to another function, create a function within a function, and even return a function. This is an extremely powerful concept, but one that is confusing for those with programming backgrounds in Java/C/C++.
Essentially, callback functions are functions that exist as a parameter for another function. They allow for the definition of functionality that exhibits some type of pattern. For example:

In the doSomethingWithArray function, we are defining a pattern of functionality that is performed on an array. The first parameter is an array and the second is a callback function. The reason callback functions are useful is because we can define any function we want that takes an array as a parameter. We can even include multiple callback functions, each with their own set of functionality. In this example, the console will print out:

Say we add another function that performs another operation on an array:

Now, the second callback function will add an element to the end of the array. We then call doSomethingWithArray passing in the original callback function, which will output to the console:

Even though this is a fairly trivial example, the intent of this blog post was to demonstrate how a callback function’s core functionality works. They allow for asynchronous execution of code within a program, and can serve as event listeners/handlers. If there are many different operations that you need to perform on a webpage with the same data, callbacks are useful by allowing you to reuse the same code for many different purposes.