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".

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 some 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"));

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

JavaScript, Function

BUY Ξ£JS JavaScript in Depth