Functional programming is a highly valued programming paradigm, so is a way of thinking about software construction by creating pure functions. It avoids concepts of shared state, mutable data observed in Object-Oriented Programming.
But what are all these buzzwords I'm talking about?
Well. As everyone knows, functions are pieces of code that can be reused once, and once again, they can receive some inputs, compute that input, and finally return an output, piece of cake, huh?
Functional code is characterized by:
- The absence of side effects.
- Pure functions.
- Stateless.
- First-class functions.
Let's find an easy way to define all these concepts.
What is a side-effect?
Side-effects are the process of modifying any variable or object property (e.g., a global variable, or a variable in the parent function scope chain).
Another side-effect would be print something into the console.
No having side effects means that the function doesn't change the outer world.
What is a pure function?
A pure function is a function which:
- Take its input and use that and only that to compute an output and then return it.
- They can't use variables either functions out of their scope.
- Produces no side effects.
Not pure function
Pure function
What does stateless mean?
That means values don't mutate.
First-class functions.
When functions are treated like any other variable.
For instance:
- Functions can be stored in variables.
- Passed around as arguments, or even returned from other functions.
How to do functional programming?
- Don't iterate, map, filter, and reduce instead.
- Use higher-order functions.
Higher-order function
A higher-order function meets at least one of the following conditions:
- Takes functions as input.
- Return another function as output.
The Holy Trinity of Functional Programming
map() instead of for
map() does not mutate the array, it makes a copy.
reduce() takes an array and return just one reduced element
Advantages of functional programming.
- They don't raise any side-effects.
- Easy to refactor.
- Better encapsulation.
- Increase reusability.
- Modularity.
- Easy to test.
Well, that's all about this brief introduction to functional programming concepts. Thank's for reading.
More information about map, filter, and reduce:
map filter reduce
Top comments (2)
Nice, but I've found few issues:
animal => animal = ":)"
make not sense you're assigning to value that is thrown away and use side effect of assignment. It should beanimal => ":)"
Example:
Great