I've been working with node.js for a while on a chat app (I know, very original, but I figured it'd be a good learning project). Underscore.js provides a lot of functional programming concepts which look interesting, so I'd like to understand how a functional program in JavaScript would be setup.
From my understanding of functional programming (which may be wrong), the whole idea is to avoid side effects, which are basically having a function which updates another variable outside of the function so something like
var external; function foo() { external = 'bar'; } foo();
would be creating a side effect, correct? So as a general rule, you want to avoid disturbing variables in the global scope.
Ok, so how does that work when you're dealing with objects and what not? For example, a lot of times, I'll have a constructor and an init method that initializes the object, like so:
var Foo = function(initVars) { this.init(initVars); } Foo.prototype.init = function(initVars) { this.bar1 = initVars['bar1']; this.bar2 = initVars['bar2']; //.... } var myFoo = new Foo({'bar1': '1', 'bar2': '2'});
So my init method is intentionally causing side effects, but what would be a functional way to handle the same sort of situation?
Also, if anyone could point me to either a Python or JavaScript source code of a program that tries to be as functional as possible, that would also be much appreciated. I feel like I'm close to "getting it", but I'm just not quite there. Mainly I'm interested in how functional programming works with traditional OOP classes concept (or does away with it for something different if that's the case).
Those first-class functions are what makes functional programming possible in JavaScript. JavaScript is a multi-paradigm language that allows you to freely mix and match object-oriented, procedural, and functional paradigms. Recently there has been a growing trend toward functional programming.
What is JavaScript? JavaScript (often shortened to JS) is a lightweight, interpreted, object-oriented language with first-class functions, and is best known as the scripting language for Web pages, but it's used in many non-browser environments as well.
Advantages Of Functional ProgrammingIt improves modularity. It allows us to implement lambda calculus in our program to solve complex problems. Some programming languages support nested functions which improve maintainability of the code. It reduces complex problems into simple pieces.
Functional programming is based on mathematical functions. Some of the popular functional programming languages include: Lisp, Python, Erlang, Haskell, Clojure, etc. Functional programming languages are categorized into two groups, i.e. −
You should read this question:
Javascript as a functional language
There are lots of useful links, including:
Now, for my opinion. A lot of people misunderstand JavaScript, possibly because its syntax looks like most other programming languages (where Lisp/Haskell/OCaml look completely different). JavaScript is not object-oriented, it is actually a prototype-based language. It doesn't have classes or classical inheritance so shouldn't really be compared to Java or C++.
JavaScript can be better compared to a Lisp; it has closures and first-class functions. Using them you can create other functional programming techniques, such as partial application (currying).
Let's take an example (using sys.puts
from node.js):
var external; function foo() { external = Math.random() * 1000; } foo(); sys.puts(external);
To get rid of global side effects, we can wrap it in a closure:
(function() { var external; function foo() { external = Math.random() * 1000; } foo(); sys.puts(external); })();
Notice that we can't actually do anything with external
or foo
outside of the scope. They're completely wrapped up in their own closure, untouchable.
Now, to get rid of the external
side-effect:
(function() { function foo() { return Math.random() * 1000; } sys.puts(foo()); })();
In the end, the example is not purely-functional because it can't be. Using a random number reads from the global state (to get a seed) and printing to the console is a side-effect.
I also want to point out that mixing functional programming with objects is perfectly fine. Take this for example:
var Square = function(x, y, w, h) { this.x = x; this.y = y; this.w = w; this.h = h; }; function getArea(square) { return square.w * square.h; } function sum(values) { var total = 0; values.forEach(function(value) { total += value; }); return total; } sys.puts(sum([new Square(0, 0, 10, 10), new Square(5, 2, 30, 50), new Square(100, 40, 20, 19)].map(function(square) { return getArea(square); })));
As you can see, using objects in a functional language can be just fine. Some Lisps even have things called property lists which can be thought of as objects.
The real trick to using objects in a functional style is to make sure that you don't rely on their side effects but instead treat them as immutable. An easy way is whenever you want to change a property, just create a new object with the new details and pass that one along, instead (this is the approach often used in Clojure and Haskell).
I strongly believe that functional aspects can be very useful in JavaScript but ultimately, you should use whatever makes the code more readable and what works for you.
You have to understand that functional programming and object oriented programming are somewhat antithetical to each other. It's not possible to both be purely functional and purely object oriented.
Functional programming is all about stateless computations. Object oriented programming is all about state transitions. (Paraphasing this. Hopefully not too badly)
JavaScript is more object oriented than it is functional. Which means that if you want to program in a purely functional style, you have to forego large parts of the language. Specifically all the object orient parts.
If you are willing to be more pragmatic about it, there are some inspirations from the purely functional world that you could use.
I try to adhere to the following rules:
Functions that perform computations should not alter state. And functions that alter state should not perform computations. Also, functions that alter state should alter as little state as possible. The goal is to have lots of little functions that only do one thing. Then, if you need to do anything big, you compose a bunch of little functions to do what you need.
There are a number of benefits to be gained from following these rules:
Ease of reuse. The longer and more complex a function is, the more specialized it also is, and therefore the less likely it is that it can be reused. The reverse implication is that shorter functions tend to more generic and therefore easier to reuse.
Reliability of code. It is easier to reason about correctness of the code if it is less complex.
It is easier to test functions when they do only one thing. That way there are fewer special cases to test.
Update:
Incorporated suggestion from comment.
Update 2:
Added some useful links.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With