You build up your program with functions. You can organize functions into modules.
A function is a reliable black box with explicit inputs and outputs. Everytime you put the same input into the function you get the exact same output. This is the mathematical definition of a function.
In mathematics, a function is a binary relation over two sets that associates to every element of the first set exactly one element of the second set.
Wikipedia, Function (mathematics) --- https://en.wikipedia.org/wiki/Function_(mathematics)
Most of the time when we talk about functions in our code they are probably not functions in the mathematical sense. They are more accurately called procedures. A chunk of code that does something. There are no guarantees that the chunk of code behaves like a mathematical function (i.e. maps values from one set to another).
- functional purity
- referential transparency
- side effect
- monad
- algebraic data type (ADT)
- declarative, imperative, procedural, structural
- reactive
Most of the time when you see a for loop what you really want is filter
, map
, or reduce
. You "declare" what you want instead of telling the computer how to do it.
const things = [1,2,3,4]
const target = 2
// find element
let foundItem = null
for (const element of things) {
if (element === target) {
foundItem = element
break
}
}
const result = things.filter(x => x === target) // result[0] === target
// or using ramda, see https://ramdajs.com/docs/#find
import * as R from 'ramda'
R.find(x => x === target, things) // returns target
- [blog post] What is a monad? --- Explain Monads like I'm five
- [YouTube video] What is the lambda calculus? --- Lambda Calculus - Fundamentals of Lambda Calculus & Functional Programming in JavaScript