JS: Functional Programing

By Xah Lee. Date: . Last updated: .

This page teaches you basic functional programing in JavaScript.

Arrow function

Here is how to define a function:

// define function
(x => (x+1));

This is called arrow function, and it is the most important tool for functional programing in JavaScript.

Be sure you learn all its details, see Arrow Function

Apply a function to a value

You can apply a function to value directly.

// apply a function to value directly
console.log( (x => (x+1))(2) ); // 3

Function's type is "function"

A function definition has a value that represents the function.

typeof operator on function returns the string "function".

console.log(
typeof (x => (x+1)) === "function"
);
 //  true

Assign a function to variable

You can assign function to variable, thus, giving it a name.

// assign a function to a variable
const f = (x => (x+1));
console.log( f(2) ); // prints 3

Function returning a function

Function can return a function.

// function returning a function
const f = ((n) =>
 (x => (n + " and " + x ))
);
console.log( f(2) (7)); // prints 「2 and 7」

So, for example, you can define a function f(n) that returns a function g(x) that computes nth power of x.

// function returning a function
const f = ((n) => (x => Math.pow(x,n)));
console.log( f(2) (4)); // 16
// f(2) returns a function that computes x^2

In the above, we first call f(2), the result is a function that computes x^2. Then, we give this function a argument of 4, so the result is 16.

Function taking a function as argument

Function can take a function as argument.

// f takes a function g as arg, and returns g(4)
const f = ((g) => (g(4)));

// this function just add 1 to arg
const h = (x => x+1);

console.log( f(h) ); // 5

Function composition

Because all the above features, JavaScript can do advanced functional programing.

For example, we can define a function (say, fCompose), that takes 2 arguments, each is a function (say, f and g), and fCompose returns a new function whose behavior is equivalent to f(g(x)).

// function composition

/* [ takes two single value functions f(x) and g(x) and returns a function that computes f(g(x)) */
const fCompose = (f, g) => ((n) => (f(g(n))));

// append "i" to string
const fi = (s) => (s + "i");

// append "j" to string
const fj = (s) => (s + "j");

console.log(
 fCompose(fi, fj)("x") === "xji",
); // true