All languages have their strengths and flaws and JavaScript is not left out – a lot of people even think it is a bad bad language full of flaws and mistakes. However I believe the language is quite beautiful and Brenden Eich certainly got some things right in its design. Douglas Crockford (know him? He’s a JavaScript advocate and invented JSON + JSLint) said JavaScript is like “Lisp in C’s clothing”; possibly due to JavaScript’s Self and Scheme roots. Scheme, one of the dialects of Lisp, is a weird cool language that uses the prefix notation (pretty strange to me coming from an infix background) and has some interesting features like first-class continuations and lambda calculus
Here are some of the functional aspects of JavaScript:
First-class functions
First-class functions
One of the core features of functional programming is supporting functions as normal data, most other languages differentiate between data and programs. Functional programming allows you to use and treat functions as you’ll treat data. As such, you can store functions in variables, create functions on the fly during execution of programs (just as you’ll create variables normally in other languages), return functions from functions, pass functions as arguments to other functions. Cool stuff right? And some sample code:
// creating and returning functions on the fly
function Counter() {
var i = 1;
return function () {++i;}
}
// assigning variables to functions
var func = function () { ... }
// passing functions as arguments
function doSomething (function callback) {
callback(arguments)
}
Closures
Closures
Now I love this one. Closures are a way of hiding your data and making them ‘private’. It is awesome and cool to use. Closures are functions that can refer to variables outside of the context they were created in.
var makeCounter = function () {
var count, f;
count = 0;
f = function () {
count = count + 1;
return count;
};
return f;
};
var counter = makeCounter();
/* counter is a function that takes no arguments and returns a count */
var a = counter();
// => 1
var b = counter();
// => 2
var c = counter();
// => 3
Closures are used to do event binding, callbacks, sorting, mapping and other stuff. An example is the jQuery sample code below:
(function() {
var jQuery=window.jQuery=window.$=function(selector,context) {
// ...
}
})();
The jQuery code is executed as an anonymous function immediately, however the variable function names, jQuery and $ are exposed and can be used outside the anonymous function. The body of the entire jQuery code is protected from manipulation by outside code, this ensures that its variables are kept hidden and enables exposing those methods that we all know and love.
Lastly…
Lastly…
There are other properties of JavaScript too such as currying, lambdas (anonymous functions), higher-order function support although it lacks some other features of functional programming languages such as tail-call optimization, it’s is variable-oriented language and has side-effects too.
Also jQuery exploits a lot of the Lisp roots of the JavaScript language; these include list processing (remember that selectors return lists) and method chaining ( I think this is just a cover for the continuation passing style).
Should you learn about functional programming? I think so; it’ll improve the way you think about programming, well I admit you might never have to use it but it should make you better.
Related articles
Related articles
JavaScript encapsulation http://www.crockford.com/javascript/private.html
JavaScript Inheritance patterns http://www.crockford.com/javascript/inheritance.html
Closures in JavaScript http://nathansjslessons.appspot.com/lesson?id=1000
Nice one! Anonymous functions and Closures are pretty similar except Closures are usually used inside your own function and the data hiding feature(most of the code I see/write). Higher-order functions; that I haven’t used and most times, you pass in an Anonymous function as an argument. I’m really looking forward to working on a hardcore JS project. With the rise of NodeJS and more awareness about the strenghts of JS, Methinks JS is coming into it’s own. A long overdue glory. :)
LikeLike
Yes. Despite its flaws it’s seeing widescale adoption and JavaScript Specialists are emerging.
You seem to use it a lot; impressive; baarakallahu feehi.
LikeLike
Wa iyakum. It has found a nice place in HTML5. I really wish I can use it more. All we seem to be doing with it is just spicing up pages, client-side validation etcetera! I want to do more than that with it; maybe work with it server side. Barakallah feeh!
LikeLike
Ameen, you should think about building whole client-side frameworks with it.
It is really powerful once you know how to use it.
LikeLike
There is a typo in your closure example. The function you define is Counter, but when you call it you call it makeCounter.
LikeLike
Thanks a lot Ian. :D
Fixed!
LikeLike
While closures are nice, you still should take extra care when using them: If you use them in loops, the garbage collector might not be able to collect them, effectively creating a memory leak (making your browser eat memory over time).
LikeLike
Interesting, I never knew that! Thanks :)
LikeLike
Basically – a closure creates a new gc root context, where you can declare variables that will not be GC’d, otherwise your counter would return ‘undefined’ after some time.
Last year I wrote a visualization webapp that died after some time exactly because of that. One part have been closure leaks in the graph library we used, we ourselves introduced some by using ajax calls to get new data via timers (we attached variables to the XMLHttpRequest object, which would call a function to create a new request object after some time, … and so on ).
LikeLike
Awesome! Thanks, great tips!!
LikeLike
Pretty awesome!
LikeLike
just came by to look at this blog. It is really great and
I liked browsing it, thanks for the great article!
LikeLike
Thanks for the nice comment; I am glad you liked it!
LikeLike
I hope You will enjoy online Functional Programming class
https://class.coursera.org/progfun-002/class/index
LikeLike
Thanks a lot!
LikeLike
Very Interesting JavaScript Functional Programming Video
LikeLike
Interesting! Thanks Mahboub!!
LikeLike
Cheers for this excellent write-ups. Keep sharing great articles!
LikeLike