In short, functional programming is a programming paradigm - style of programming - built around the concept of 'pure' functions; functions that take inputs and return an output without affecting anything else in the program.
Here are some of the main concepts in functional programming:
Pure functions are functions with no side effects; meaning whatever happens inside the function, stays inside the scope of the function until the return statement. These functions don't change global state or even log outputs, nor do they take in any input other than what is passed in as a parameter.
Simply put: A pure function will take in arguments, perform internal calculations without using or changing any external state, and then return a value.
Since nothing is nothing is changed or affected by state outside of a pure function, then you can assume the following: given the same input, you always get the same output. This makes pure functions easier to test and debug. You know what to expect from them and they are easier to reason about.
Immutability is the idea that you declare variables, set them equal to a value, and then that value doesn't change over time. For example, if you set
var x = 4, you cannot later say
x = 10 or
x = 'hello'. That is called mutating state and is not allowed in functional programming. If you need a new value, you have to declare a new variable rather than change the old one.
const when declaring a variable, and using the
Object.freeze() method to disallow certain types of object mutations. It's not a perfect system but is definitely beneficial in avoiding accidental state mutations.
Again, this makes debugging simpler because once a variable is set, you know it's not going to change. This allows you to safely make certain assumptions about your code.
Function composition is the idea of breaking up functions into smaller functions, where each function is ideally only doing one thing, and then composing them together.
add5 function composes the
add2 functions into a single interface. Each function performs one piece of the process.
Hope you enjoyed this mini-article. Buckle up for several more weeks of articles on functional programming! :)