Functional programming, or programming in the "function paradigm" is an approach to programming where functions are "first class". This is in contrast to the object-oriented paradigm, which prioritizes classes and class methods over stand-alone functions.
In a tech talk by Russ Olsen for the "goto; conference", Functional Programming in 40 Minutes or Less, Russ argues that the functional paradigm is about 3 things:
-
Pure functions
- A poorly named phrase that "simply" looks at parameters and generates output
-
Immutable data structures
-
Bridges to the outside world
Taken together, the implication is that the "inside world" is insular, i.e., chains of pure functions immutably transforming inputs into outputs.
Russ also thinks it is fair to be confused by the differences between FP and OOP because you keep most everything unchanged. To paraphrase him, I would claim that the real difference is where your functions and data are. The actual functions are essentially the same. and actual data will look mostly the same.
Example
The following is code written in a functional paradigm
const person = { name: "Alice" };
function greeting(person) {
console.log(`Hello, my name is ${person.name}`);
}
greeting(person);
The following is code written in an object-oriented paradigm
class Person {
constructor(name) {
this.name = name;
}
greeting() {
console.log(`Hello, my name is ${this.name}`);
}
}
const person = new Person("Alice");
person.greeting();
The differences are "where"-based. Where is the data, where are the functions. The greeting
function itself is basically identical between the two. The difference between this.name
and person.name
is mutability. this.name
could have mutated is other methods updated the name
attribute of Person
. In the fp style person.name
is immutable. There is no way to change the value of a simple data payload.