Functional JS

101

The world is full
of lists

It's usually either
🐶 or [🐶, 🐶, 🐶]

It's all lists.
We need tools to work with lists

map

creates a new array with the result of calling the provided function for each value in the array

const list = [1, 2, 3, 4]

const squares = list.map(a => a * a)

console.log(squares) // [1, 4, 9, 16]

Live code šŸ¤“

filter

creates a new array including only the values where the function returns a truthy value when called with the value

šŸ¤”

const list = [1, 2, 3, 4, 5]

const evenNumbers = list.filter(
  number => number % 2 === 0
)

console.log(evenNumbers) // [2, 4]

Live code šŸ¤“

reduce

incrementally build a value while iterating over the values in the array, passing the result of the last step into the next

really confusing at
first. we know..

const list = [1, 2, 3, 4]

const sum = list.reduce(
  (res, value) => res + value,
  0
)

console.log(sum) // 10

Live coding šŸ¤“

find

find the first element in an array that the function returns a truthy value for

const animals = ['🐶', 'šŸ', '🐱']

const cat = animals.find(
  animal => animal === '🐱'
)

console.log(cat) // '🐱'

Live coding šŸ¤“

findIndex

find the index of the first element in an array that the function returns a truthy value for

const animals = ['🐶', 'šŸ', '🐱']

const catIndex = animals.findIndex(
  animal => animal === '🐱'
)

console.log(catIndex) // 2

Live coding šŸ¤“

Functional JS 101

By Kristoffer Brabrand

Functional JS 101

  • 592