JS: Functional Programing

By Xah Lee. Date: . Last updated: .

This page teaches you basic functional programing in JavaScript.

Arrow Function

Here's 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 JS: 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 computs 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.

// function taking 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

JS Function

  1. Define Function
  2. Arrow Function ⭐
  3. Function Params
  4. “arguments” Object
  5. Rest Params ⭐
  6. Arg Default Value ⭐
  7. Arg Destructure ⭐
  8. f Declaration vs Expression
  9. Closure
  10. f call apply bind
  11. Functional Programing

Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials