Practical introduction to Functional Programming with JS

legendtariq
1,218 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Functional programming is one of those things that you probably heard about, but never approached, because it looked too hard, too theoretical; well wait no more, because in this course you will be introduced to functional programming through examples and exercises in a familiar language: JavaScript.
As a reference, here are the topics we'll talk about:

  • Pure functions
  • Higher Order Functions
  • Currying
  • Recursion
  • Functors
  • Monads

You need to know basic JavaScript usage, if you never programmed in JavaScript you can checkout this quick intro and come back, I'll wait for you.

Open Source is <3, so here is the repository for this playground, feel free to contribute, clone,

Pure Functions

I admit it, I lied to you: we need a tiny bit of theory to get started.
One key concept of functional programming is that functions should not have side-effects and should not depend on external state, i.e. a function should takes some input and returns some output without modifying or accessing any value outside the function.

A sign that a function is impure is if it makes sense to call it without using the return value; you will never do that with a pure function.
To be clear, this is a pure function:

function add2 (x){
  return x + 2
}

And this is not:

var y = 2
function adder (x){
  return x + y
}

The great benefit of pure functions is that their output is deterministic: given some inputs it will always return the same value, this makes them extremely easy to debug. E.g. our add2 function from before given the input 12 will always return 14

Now time for some code:

Implement the pure function `greet` following the specification
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function greet(name) {
// write your code here
}
/*
EXPECTED BEHAVIOUR:
console.log(greet("Alex"))
> Hi, Alex
console.log(greet("John"))
> Hi, John
*/
// {...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content