JavaScript: The functional Programming Parts
Yes, a lot of people think JavaScript is just another object-oriented language but the language differs in many ways from the Java/C++ class of programming languages. For example, JavaScript uses prototypical inheritance versus the classical inheritance favoured by OO languages; this makes it easier to get on new behaviours… and also makes it really really easy to shoot yourself in the foot.
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
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:
function Counter() {
var i = 1;
return function () {++i;}
} //creating and returning functions on the fly
var func = function () { ... } //assigning variables to functions
function doSomething (function callback) {
callback(arguments)
}//passing functions as arguments
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…
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
- 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
- http://www.ajaxonomy.com/comment/reply/690
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.
Umar Farouq Khattab
July 9, 2012 at 7:25 am
Yes. Despite its flaws it’s seeing widescale adoption and JavaScript Specialists are emerging.
You seem to use it a lot; impressive; baarakallahu feehi.
AbdulFattah Popoola
July 9, 2012 at 3:31 pm
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!
Umar Farouq Khattab
July 10, 2012 at 6:41 am
Ameen, you should think about building whole client-side frameworks with it.
It is really powerful once you know how to use it.
AbdulFattah Popoola
July 11, 2012 at 3:45 am
[...] JavaScript: The functional Programming Parts (abdulapopoola.wordpress.com) [...]
How to Add a Character Counter to the WordPress Post Excerpt Box « 12oy.wordpress.com
July 9, 2012 at 10:11 am
There is a typo in your closure example. The function you define is Counter, but when you call it you call it makeCounter.
Ian
July 12, 2012 at 1:33 pm
Thanks a lot Ian.
Fixed!
AbdulFattah Popoola
July 12, 2012 at 2:59 pm
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).
vxl23
July 13, 2012 at 5:42 am
Interesting, I never knew that! Thanks
AbdulFattah Popoola
July 13, 2012 at 12:05 pm
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 ).
vxl23
July 13, 2012 at 2:39 pm
Awesome! Thanks, great tips!!
AbdulFattah Popoola
July 16, 2012 at 3:19 am
Pretty awesome!
Umar Farouq Khattab
July 16, 2012 at 6:48 am
[...] other language is currently experiencing rapid widespread adoption on all major platforms? Read this and this if you want to know [...]
Clean Code, Dirty Code « CodeKraft
August 25, 2012 at 4:30 am
[...] you like this post? Check out my other posts on JavaScript, its functional programming parts and a book [...]
Events in JavaScript « CodeKraft
February 17, 2013 at 2:55 am
just came by to look at this blog. It is really great and
I liked browsing it, thanks for the great article!
iphone wooden case
March 3, 2013 at 6:46 pm
Thanks for the nice comment; I am glad you liked it!
AbdulFattah Popoola
March 3, 2013 at 7:34 pm
[...] an example); for these private properties you’ll have to add accessors and setters; read this for an explanation of closures and this [...]
Static and Instance Methods in JavaScript | CodeKraft
March 30, 2013 at 10:47 am
I hope You will enjoy online Functional Programming class
https://class.coursera.org/progfun-002/class/index
محبوب الرشيد
March 31, 2013 at 4:24 pm
Thanks a lot!
AbdulFattah Popoola
March 31, 2013 at 6:19 pm
Very Interesting JavaScript Functional Programming Video
http://vimeo.com/49384334#at=0
محبوب الرشيد
April 2, 2013 at 6:05 pm
Interesting! Thanks Mahboub!!
AbdulFattah Popoola
April 2, 2013 at 7:15 pm