Functional programming is a declarative programming paradigm that allows you to do many things in a single line of code. By composing small modular functions, you can tell a computer what you want it to do instead of how to do it. Functional programming is called that because, as the name implies, programs consist almost entirely of functions. The core principles of functional programming are as follows:
- Pure functions—Functions return the same value for the same arguments, never having any side effects.
- First-class and higher-order functions—Functions are treated like any other variables and can be saved, passed around, and used to create higher-order functions.
- Immutability—Data is never directly modified. Instead, new data structures are created each time data would change.
To give you an idea of the difference between procedural and functional programming, here is some procedural JavaScript code that multiples all even numbers in an array by 10 and adds the results together:
const numList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] let result = 0; for (let i = 0; i < numList.length; i++) { if (numList[i] % 2 === 0) { result += (numList[i] * 10) } }