Quick Introduction — Functional Programming With JavaScript

What is functional programming?

  • A programming paradigm
  • coding style
  • mind set

Why functional programming in JavaScript?

JavaScript is a high-level, dynamic, weakly typed, object-based, multi-paradigm, and interpreted programming language.
The design goal of such languages is to allow programmers to use the most suitable programming style and associated language constructs for a given job
  • OOJS gets tricky with prototypes and this
  • safer, easier to debug/ maintain
  • Re-use more code
  • established community

Get Started!

Not functional:

let name = “Tzuyuan”;
let greeting = “Hi, I am ”;
console.log(greeting + name); //”Hi, I am Tzuyuan”

Functional:

function greet(name) {
return "Hi, I'm " + name;
}
greet("Tzuyuan"); //"Hi, I'm Tzuyuan"

Features of FP!

  • use “pure” functions (Avoid side effects!)
var xs = [1, 2, 3, 4, 5];

// pure
xs.slice(0, 3);
//=> [1, 2, 3]

xs.slice(0, 3);
//=> [1, 2, 3]

xs.slice(0, 3);
//=> [1, 2, 3]


// impure
xs.splice(0, 3);
//=> [1, 2, 3]

xs.splice(0, 3);
//=> [4, 5]

xs.splice(0, 3);
//=> []
  • another example
//Not pure
let name = "Tzuyuan";
function greet() {
console.log("Hi, I'm " + name);
}
//pure
function greet(name) {
return "Hi, I'm " + name;
}
  • use higher-order functions

example: Don’t iterate over lists

Composition!

  • avoid mutability

Composition over Inheritance

A little bit introduction of Currying…

You can call a function with fewer arguments than it expects. It returns a function that takes the remaining arguments.
You can choose to call it all at once or simply feed in each argument piecemeal.

log out:
fluffykins is a tiny dragon that breathes lightning!

user lodash to currying:

Will get the same result!

Reference

https://github.com/MostlyAdequate/mostly-adequate-guide
mostly-adequate-guide

https://www.youtube.com/watch?v=e-5obm1G_FY&t=1361s
Anjana Vakil: Learning Functional Programming with JavaScript — JSUnconf 2016

https://www.youtube.com/watch?v=BMUiFMZr7vk&list=PL0zVEGEvSaeEd9hlmCXrk5yUyqUag-n84
FunFunFunction Functional Programming in JavaScript series

https://en.wikipedia.org/wiki/Programming_paradigm#Multi-paradigm
Multi-paradigm

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.