Discover Functional JavaScript was named one of the best new Functional Programming books by BookAuthority!
In JavaScript, functions are first-class objects, which means they can be:
- stored in a variable, object, or array
- passed as an argument to a function
- returned from a function
Storing a function
Functions can be stored in three ways:
- store in a variable :
let fn = function doSomething() {}
- store in an object :
let obj = { doSomething : function(){} }
- store in an array :
arr.push(function doSomething() {})
In the first and third example, I used a named function expression.
The function expression defines a function as part of a larger expression. The line of code doesn’t start with function
.
Function as an argument
In the next example, the function doSomething
is sent as an argument to doAction()
.
doAction(function doSomething(){});
doSomething
is a callback.
A callback is a function passed as an argument to another function.
Higher order functions
A higher order function is a function that takes another function as an input, returns a function or does both.
You can find more in the Discover Functional JavaScript book.
For more on applying functional programming techniques in React take a look at Functional React.
Learn functional React, in a project-based way, with Functional Architecture with React and Redux.