What is functional programming?
- a programming paradigm
- a coding style
- a mindset
- a sexy, buzz-wordy trend
Why functional JavaScript?
- object-oriented JS gets tricky (prototypes? this ?!?)
- safer, easier to debug/maintain
- established community
OK, let’s do it!
...how?
Do everything with functions
input -> output
Not functional:
var name = “Lakshya”;
var greeting = “Hi, I’m ”;
console.log(greeting + name);
=> “Hi, I’m Lakshya”
Functional:
function greet(name) {
return “Hi, I’m ” + name;
}
greet(“Lakshya”);
=> “Hi, I’m Lakshya”
Avoid side effects
use “pure” functions
Not pure:
var name = “Lakshya”;
function greet() {
console.log(“Hi, I’m ” + name);
}
Pure:
function greet(name) {
return “Hi, I’m ” + name;
}
Use higher-order functions
functions can be inputs/outputs
function makeAdjectifier(adjective) {
return function (string) {
return adjective + “ ” + string;
};
}
var coolifier = makeAdjectifier(“dev”);
coolifier(“to”);
=> “dev to”
Don’t iterate
use map, reduce, filter
Source: https://www.datasciencecentral.com/forum/topics/what-is-map-reduce
Avoid mutability
use immutable data
Mutation (bad!):
var rooms = [“H1”, “H2”, “H3”];
rooms[2] = “H4”;
rooms;
=> ["H1", "H2", "H4"]
No mutation (good!):
var rooms = [“H1”, “H2”, “H3”];
Var newRooms = rooms.map(function (rm) {
if (rm == “H3”) { return “H4”; }
else { return rm; }
});
newRooms;
=> ["H1", "H2", "H4"]
rooms;
=> ["H1", "H2", "H3"]
Top comments (0)