Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a good example for functional style web programming using javascript?

I'm doing javascript on a daily basis at the moment. I'm coming from an OO background and most of the code I have contact with is somewhat procedural/OO style. I'm looking for good examples that solves more or less typical web programming tasks but in a functional manner.

I'm not interested to have any arbitrary example that just looks like functional. I'm looking for an example that can show how to use the functional powers to solve problems better than with another approach. I know this is kind of subjective/style dependent but don't make it too hard for yourself (myself).

like image 245
Norbert Hartl Avatar asked May 06 '09 21:05

Norbert Hartl


2 Answers

Firstly, you want to comprehend what functional programming means; that is, what are the core concepts and how well the language allows you to adhere to those concepts. For OOP, the core concepts are encapsulation, inheritance, and polymorphism (or just message passing for smalltalkers). For FP the central tenet is referential transparency (which implies statelessness). Trying to program in a functional style in a language that doesn't support functional features (e.g. functions as first class objects) will be awkward if not impossible. Same with programming in OOP in languages that don't have OOP features.

Fortunately Javascript is multi-paradigm and supports both. Instead of looking for examples of code that is 'functional' just think about all the ways in which you can ensure referential transparency and this will naturally lead to using the FP features of the language such as lambdas, closures, higher-order functions (e.g. map, reduce, filter), currying, etc.

Seriously, this is not meant to be a non-answer. I really think this is the most motivating and efficient way of approaching it.

That said, here are some hopefully helpful links.

  1. FP programming in JavaScript

  2. Mostly adequate guide to FP

like image 80
Rodrick Chapman Avatar answered Sep 22 '22 13:09

Rodrick Chapman


Douglas Crockford links to Functional JavaScript from his JavaScript resource page. Here is a snippet from the site:

Functional is a library for functional programming in JavaScript. It defines the standard higher-order functions such as map, reduce (aka foldl), and select (aka filter). It also defines functions such as curry, rcurry, and partial for partial function application; and compose, guard, and until for function-level programming. And all these functions accept strings, such as 'x -> x+1', 'x+1', or '+1' as synonyms for the more verbose function(x) {return x+1}.

like image 26
Kevin Hakanson Avatar answered Sep 20 '22 13:09

Kevin Hakanson