DEV Community

Lakshya Tyagi
Lakshya Tyagi

Posted on • Edited on

Learning Functional
Programming with JS

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, Im ;
console.log(greeting + name);
=> Hi, Im Lakshya
Enter fullscreen mode Exit fullscreen mode

Functional:

function greet(name) {
return Hi, Im  + name;
}
greet(Lakshya);
=> Hi, Im Lakshya
Enter fullscreen mode Exit fullscreen mode

Avoid side effects

use “pure” functions

Not pure:

var name = Lakshya;
function greet() {
console.log(Hi, Im  + name);
}
Enter fullscreen mode Exit fullscreen mode

Pure:

function greet(name) {
return Hi, Im  + name;
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Don’t iterate

use map, reduce, filter

Alt Text

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"]
Enter fullscreen mode Exit fullscreen mode

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"]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)