2011 was also when I had to dig into Scala. Thus I was compelled to implement more solutions in a functional manner.
Like many programmers unfamiliar with Functional Programming or others familiar with Functional Programming but more comfortable with Object Oriented Programming, it was daunting at first.
But persist through and one starts to see the benefits of Functional Programming (or at least understand it enough and execute your projects).
In fact, all function declarations are automatically converted to function expressions and hoisted.
By hoisting, the converted function expression is automatically placed in the beginning and thus is available in lines before it has been declared.
By dynamic arguments, I mean, in the function body, we are provided an arguments array which contain all the arguments sequentially in the order they were passed. This means any function can be called with any set of arguments, thus giving us a lot of flexibility.
By dynamic context, I am refering to the this object. Typically the this object defaults sensibly to the context of the function. However it is possible to explicitly call a function with a user defined this / context object.
functionName.apply() allows us to explicitly set the context and pass arguments.
Another trick for you is the capability to define self-executing anonymous function. These can be creatively used to implement modular namespaces / packages. Here are some examples:
Higher Order Functions
The answer to both questions is “Yes”. And such functions which taking in other functions are arguments and / or return functions are typically called higher order functions.
In the example below, we will define a higher order function
forEach. This function takes in two
list and an
action. The first argument list is an array containing containing
objects and the second argument action is a function that will be invoked for each item in list.
The simple example above shows how a named function
logItem and an
anonymous function are
being passed as arguments to the higher order function
Map / Reduce Implementations
In the example above, we saw how the
forEach algorithm was expressed as a function and reused multiple
times as an when required. We avoided repeating loops and thus made the code more readable.
This is one of the prime reasons to write functional code. If done correctly, you’ll be able to abstract out complex algorithms, replace it with a nice function call and keep code condensed and readable.
To further stress this idea, we need a better example. For each was too simple an algorithm to abstract. Let’s try implementing higher order functions for Map and Reduce algorithms.
We start with the Map function. What is the map function? Our
map function should allow the user to
perform a particular action over each item of a
list, and then return a
containing results of actions performed on each list item.
Simple enough, show me the code!
Notice we reuse the
forEach function from the previous example. Our
map function takes in
two arguments, the first one being the
mappingFunction that is to be applied on every item of the second
The implementation for
map is straightforward. We prepare an array result, iterate through the list,
mappingFunction for each item in
list, push the result in the result array return
it when all done.
As an example, we are calling map function and passing the function
doubleIt as the
mapperFunction on each item of an anonymous list.
Time for the
reduce function. What is the reduce algorithm? The
reduce function will be
combine function, a
base value and a
list. We need to apply the
function on the base value and each value in the list and finally return the result. In short, Reduce function takes
in a list, combines it and gives us a single result.
This solution again makes use of the previous create
forEach function. Our
is simple, it iterates through the
base and each list
item, stores the result in base and returns it after completion.
As a usage example, we use
reduce to get a count of the negative numbers in a list.
These two examples are fairly simple and still show us how, with functional programming, we can effectively abstract out algorithms as functions, use them as and when required and still retain simplicility and readability in the code.
If you’ve heard of Functional Programming, there’s a very good chance you’ve also heard about closures. They are often mentioned in the same breath.
But what are closures? Think of closures as a composite of two things:
- A function being returned by another function
- A closed environment in which this returned function is forced to execute
This is what a closure is.
In our first example of a closure implementation, we have
getAreaFunction which reads the shape argument
and returns an appropriate area function.
getAreaFunction returns an anonymous function. This returned function contains a switch case
on shape which is available in the environment.
Finally, of course, we see how to use the closure as a function factory to get area functions for different types of shapes.
Shape (which is, yes, expressed as a function) contains a private function
area and isn’t
Instead an instance function
getArea is available which does internally make use of the private function
Consider the following example:
In the for loop, we first assign an
onclick handler to all the red boxes. However, thanks to functional
scoping, all three red boxes have onclick handlers with
redBoxId value 3.
However for green boxes we assign
onclick handlers in a slightly different manner. We have a self
executing anonymous function which returns another function which then is assigned as the onclick handler.
Due to functional scopes, each
onclick handler for the green boxes have correct values for
All code available on GitHub.