Functional Javascript 101

 

javascript-graphicJavaScript is a real language and it was during my first job as a Salesforce Developer that I was able to start learning the “language.” I remember adding a script on a visual force page and selecting elements while using classes. Not the best practice… but it was my first encounter with the language and I knew that it would take time to truly understand the fundamentals. At the time I didn’t imagine the capabilities of the technology and how it was going to evolve and improve the way that we surf the web.

In the sense of paradigms I would say that I started writing JS code in the Imperative way, just defining functions and encapsulating logic to then use all those gears on a single purpose: fire a function onclick to show a modal window. Wow! Really impressive right? Just kidding.

[javascript]function sayMyName() {
alert(“You’re Heisenberg”);
}
document.getElementById(“my_button”).onclick = sayMyName;[/javascript]

At the same time during my first job I started attending classes at the university and in one of my classes, “Programming 2” we started to learn the famous: Object Oriented Programming, and then I started to implement this knowledge in my daily front-end work. I was able to think more on the responsibility that an object needs to have and the context where that object is going to hangout.

(function() {
"use strict";
var Heisenberg = function() {
this.name = ‘Heisenberg’;
}
Heisenberg.prototype.sayMyName = function() {
alert(“You’re ” + this.name);
};
document.getElementById("my_button").addEventListener("click", function(e) {
var heisenberg = new Heisenberg();
heisenberg.sayMyName();
});
}());

Of course the object-oriented paradigm is much easier to understand than the imperative one, and it’s also more modular.

But then I discovered a new way of thinking about my JS code: the functional way. This doesn’t mean that object-oriented is better or worse, but it’s another way of tackle situations. Let’s see:

 

This solution looks shorter, because I am only using two functions (besides I have added a static return value on the getName function). You don’t need to forget everything you know to take advantage of the functional paradigm. I would say think more on the dependencies of the functions in the context in which they are called in order to know how to structure all the code.