It would be quite far-fetched to call JavaScript a functional language, for it lacks many more sophisticated features from the FP paradigm – like tail recursion or automatic currying. This puts it on par with many similar languages which incorporate just enough of FP to make it useful but not as much as to blur their fundamental, imperative nature (and confuse programmers in the process). C++, Python or Ruby are a few examples, and on the surface JavaScript seems to place itself in the same region as well.
Except that it doesn’t. The numerous different purposes that JavaScript code uses functions makes it very distinct, even though the functions themselves are of very typical sort, found in almost all imperative languages. Learning to recognize those different roles and the real meaning of function
keyword is essential to becoming an effective JS coder.
So, let’s look into them one by one and see what the function
might really mean.
If you’ve seen few good JavaScript libraries, you have surely stumbled upon the following idiom:
Any and all code is enclosed within an anonymous function
. It’s not even stored in a var
iable; it’s just called immediately so its content is just executed, now.
This round-trip may easily be thought as if doing absolutely nothing but there is an important reason for keeping it that way. The point is that JavaScript has just one global object (window
in case of web browsers) which is a fragile namespace, easily polluted by defining things directly at the script level.
We can prevent that by using “bracketing” technique presented above, and putting everything inside this big, anonymous function. It works because JavaScript has function scope and it’s the only type of non-global scope available to the programmer.
So in the example above, the function
is used to confine script’s code and all the symbols it defines. But sometimes we obviously want to let some things through, while restricting access to some others – a concept known as encapsulation and exposing an interface.
Perhaps unsurprisingly, in JavaScript this is also done with the help of a function
:
What we get here is normal JS object but it should be thought of more like a module. It offers some public interface in the form of increment
and getValue
functions. But underneath, it also has some internal data stored within a closure: the value
variable. If you know few things about C or C++, you can easily see parallels with header files (.h, .hpp, …) which store declarations that are only implemented in the code files (.c, .cpp).
Or, alternatively, you may draw analogies to C# or Java with their public and private (or protected) members of a class. Incidentally, this leads us to another point…
Let’s assume that the counter
object from the example above is practical enough to be useful in more than one place (a tall order, I know). The DRY principle of course prohibits blatant duplication of code such as this, so we’d like to make the piece more reusable.
Here’s how we typically tackle this problem – still using only vanilla function
s:
Pretty straightforward, right? Instead of calling the function on a spot, we keep it around and use to create multiple objects. Hence the function becomes a constructor for them, while the whole mechanism is nothing else but a foundation for object-oriented programming.
We have now covered most (if not all) roles that functions play when it comes to structuring JavaScript code. What remains is to recognize how they interplay with each other to control the execution path of a program. Given the highly asynchronous nature of JavaScript (on both client and server side), it’s totally expected that we will see a lot of functions in any typical JS code.
Many of them – likely most – are callbacks to be invoked when some asynchronous operation has finished. Whether it’s an AJAX request in the browser or an I/O call done by node.js on the server, it’s through callback function that we are notified of its completion. The result, if any, is therefore passed as parameter:
Written this way, the asynchronous code reads almost exactly like the synchronous one. However, in general this ceases to be true for any more complicated cases, such as issuing more than one simultaneous call and requiring for any/all of them to complete. And even for non-parallel, sequential algorithms we may quickly encounter the problem of “marching callbacks”, resulting in what is often called a callback spaghetti:
Trying to alleviate that problem by using two-space indents (rather than more sensible four-space ones) doesn’t seem like a satisfactory solution, though. Fortunately, there are some better ways to structure asynchronous computation.
For an example, look at execution patterns implemented by the async.js library. The one that directly addresses the callback problem is either async.series
or async.waterfall
:
It does so by forming a kind of asynchronous pipeline whose elements are, of course, functions of particular form. Besides getting the current result as argument, those functions also receive a continuation (here, next
) which is called when we’re ready to advance to the next element in the pipeline. Naturally, this continuation is also a function – a special one prepared by async.waterfall
routine.
So indeed, there is usually plethora of function
s littering any non-trivial JavaScript code. Moreover, the sheer amount of different constructs they try to emulate is a tricky gotcha that not many programmers seem to be aware of.
In this post I tried to outline the most common design patterns in JavaScript that involve a clever use of plain ol’ functions. I’m pretty sure, though, that there are still many which I simply haven’t encountered yet. Hence I advise everyone working with JavaScript to pay close attention to them. Quite often it’s not really the function that the function
is about.
Adding comments is disabled.
Comments are disabled.