functions; foreach; map;
filter; reduce;
refresher: tell me all you know about functions
refresher
- functions should be simple
- functions should only do one thing
- simple functions allow us to build re-useble parts
- functions can return a value
// named functions
const doTheThing = () =>{
console.log("starting the thing")
}
//later
doTheThing()
// anonymous functions
document.addEventListener('DOMContentLoaded', () => {
console.log("do the thing here")
})
// return a value
const sum = (x, y) => {
return x + y;
}
// create and return something new
const createListItem = name => {
const li = document.createElement('li')
li.textContent = name
return li
}
Problem
For loops can very useful, but very tedious to use, hard to keep track off and can easily let use create "spaghetti code".
Solution
Instead of a for loop, we use take the patterns that for loops create, and create simpler methods that emphasize simplicity, readability and reuse
foreach
for (let i = 0; i < people.length; i++){
console.log(people[i])
showGreatingToPerson(people[i])
addPersonToDOM(people[i])
}
foreach
people.forEach(person => {
console.log(person)
showGreatingToPerson(person)
addPersonToDOM(person)
})
image credit of: https://www.wenovio.com/2017/04/11/javascript-manipuler-vos-donnees-mapfilterreduce/
const sammy = {
name: "Sammy P",
birthday:{
day:"14",
month:"Mar",
year: 1988
},
shirt:"orange",
apples: 5
}
map
const birthdays = []
for(int i = 0; i < people.length; i++){
const _bday = people[i].birthday.month +
'/' +
people[i].birthday.day
birthdays.push(_bday)
}
map
const birthdays = people.map(person => {
return person.birthday.month +
'/' +
person.birthday.day
})
filter
const orangeShirtedPeople = []
for(let i = 0; i < people.length; i++){
if (people[i].shirt === "orange"){
orangeShirtedPeople.push(people[i])
}
}
console.log(orangeShirtedPeople)
filter
const orangeShirtedPeople = people.filter(person => {
return person.shirt === "orange"
})
reduce
let totalApples = 0;
for(let i = 0; i < people.length; i++){
totalApples += people[i].apples
}
reduce
const totalApples = people.reduce((total, person) => {
return total += person.apples
}, 0)
image credit of: https://www.wenovio.com/2017/04/11/javascript-manipuler-vos-donnees-mapfilterreduce/
foreach, map, filter, reduce
By Mark Dewey
foreach, map, filter, reduce
- 939