You are on page 1of 10

Functional

Programming
(Javascript)
Recap
● Functions are values in javascript, like strings, numbers etc.
● They can be passed around to variables.

let triple = (x) => {


return 3*x
}
let anotherVariable = triple
anotherVariable(20)
Higher Order Functions
Functions that accept other functions as parameter. For example:-

● filter()
● find()
● map()
● reduce()

Higher order functions are the building block of functional programming. They
help in composition of code using small functions.
let animals = [
{ name: 'Fluffykins', species: 'rabbit' },
{ name: 'Caro', species: 'dog' },
{ name: 'Hamilton', species: 'dog' },
{ name: 'Harold', species: 'fish' },
{ name: 'Ursula', species: 'cat' },
{ name: 'Jimmy', species: 'fish' }
]
// Regular way of filtering
let dogs = []
for(animal in animals){
if(animal.species == 'dog')
dogs.push(animal)
}
// Functional programming way
let isDog = (animal) => animal.species == 'dog'
let dogs = animals.filter(isDog)
Quick Look at Functions
/* Filter is a array /* Map is also an array manipulation
manipulation function that function that takes a callback function
takes a callback function and return an array of equal size
and returns subset of array */
*/
let isDog = (animal) => { Let introOfAnimal = animals.map((animal)=>
return animal.species == `${animal.name} is a ${animal.species}.`)
'dog'
}
let dogs =
animals.filter(isDog)
/*Find returns the first element /*Reduce is a multitude function we can
that satisfies the criteria given use it to apply any array
in callback function transformation
*/ */
let cat = animals.find((animal)=> var orders = [
animal.species == 'cat') { amount: 250 },
{ amount: 400 },
{ amount: 100 },
{ amount: 325 }
]
var totalAmount = orders.reduce(
(sum, order) => {
return sum + order.amount
}, 0)
Composition of Functions
let numberOfDogs = animals.filter((animal) => animal.species == 'dog')
.map((animal) => 1)
.reduce((total, dog) => {return total +
dog[0]},0)
Advantages of Functional Programming
● Less development code which means less time for development.
● Easy debugging. As we may have noticed there is only one task per
function, which is the recommended way of coding in Javascript.
● Reusability of code. We are using built-in functions of Javascript and also
we can pass around functions to different higher order functions.
● Composition. Using smaller functions in other functions to compose the
code.
Disadvantages
● You will need to remember the syntax.
● If you feel like that you have a better optimized solution you can use it,
instead of going for higher order functions.
Bibliography

● https://www.youtube.com/watch?v=BMUiFMZr7vk&list=PL0zVEGE
vSaeEd9hlmCXrk5yUyqUag-n84
● https://developer.mozilla.org/en-US/docs/Web/JavaScript

You might also like