Functional Programming in JavaScript
© Yariv Gilad
What is functional Programming?
© Yariv Gilad
What is functional Programming?
It is a programming paradigm
(like imperative, OOP etc…)
© Yariv Gilad
What is functional Programming?
It is a coding style,
a way to organize your code...
© Yariv Gilad
What is functional Programming?
It is a mindset,
a way of thinking about a problem
or an attitude while approaching a task
© Yariv Gilad
Why functional JavaScript?
© Yariv Gilad
Why functional JavaScript?
Because there must be
a better way then writing
OOP in JS...
JavaScript is not Java!
© Yariv Gilad
Why functional JavaScript?
Because FP is an easier mental model
input => output
and JS is a good fit for it
© Yariv Gilad
Why functional JavaScript?
FP is predictable => easier to test & Maintain
Write less code
with less bugs
in less time!
© Yariv Gilad
Why functional JavaScript?
Reuse your code
using Function composition
Your app is made out of small testable units
you can use and reuse all over
© Yariv Gilad
Why functional JavaScript?
Because it has a vibrant community
full of references and support
© Yariv Gilad
Ok, let's get to it then...
© Yariv Gilad
Do everything with functions
Regard your app as a flow of communication between small bits of processes
input => output
© Yariv Gilad
Not functional:
var name = "Ajar";
var greeting = "Hi, I'm ";
console.log(greeting + name);
// => "Hi, I'm Ajar"
© Yariv Gilad
Functional:
function greet(name) {
return "Hi, I’m " + name;
}
greet("Ajar");
// => "Hi, I’m Ajar"
© Yariv Gilad
Avoid side effects
Use pure functions
a Side effect is referencing or modifying anything outside of a function scope, its input or output
Side effects leads to unpredictable buggy code
© Yariv Gilad
Not pure:
var name = "Ajar";
function greet() {
console.log("Hi, I’m " + name);
}
© Yariv Gilad
Pure:
function greet(name ) {
return "Hi, I’m " + name;
}
© Yariv Gilad
Use higher-order functions
functions can be inputs/outputs
© Yariv Gilad
Higher-order functions
function makePrefixer(prefix) {
return function (string) {
return prefix + " " + string;
}
}
var coolifier = makePrefixer("cool");
coolifier("workshop");
// => "cool workshop"
var awesomer = makePrefixer("awesome");
awesomer ("workshop");
// => "awesome workshop"
© Yariv Gilad
Replace loops with
map, reduce, filter, reject...
© Yariv Gilad
The Map Reduce Sandwich
© Yariv Gilad
Functional programming in JavaScript
By Yariv Gilad
Functional programming in JavaScript
- 1,327