Callback Functions Challenge: For Each

The .forEach() array method has ceased to exist and everyone is panicking! How will they ask Javascript to run a function with each element in an array?

Your job is to recreate the .forEach() method as a forEvery() function.

Your function should take two parameters:

  1. An array – this contains the items that need to have something done with each of them
  2. A callback function – the function that knows what to do with each item

Your function should call the callback function once for each item in the array, with that item passed in as an argument to the callback function.

So if we called the forEvery function like this:

const words = ["these", "are", "words"];
forEvery(words, alert)

The computer should call alert three times like this:

alert("these")
alert("are")
alert("words")

Tip: We don’t actually want to put these exact lines of code in our function, because we want this to work with any array of any length (not just that array of words), and with any function (not just alert)

Tests

Test #1

If we use it like this:

const numbers = [1, 5, 7, 4, 8, 8];
let sum = 0;
// For every number, add it to the sum
const addToSum = (number) => sum += number;
forEvery(numbers, addToSum)
    
// The sum should now be 33
console.log(sum)

It should add all the numbers together and sum should be 33.

Test #2

If we use it like this:

const votes = ["cat", "dog", "cat", "cat", "fish"];
let catVotes = 0;
const countCatVotes = (vote) => {
  if(vote === "cat") {
    catVotes++;
  }
}
forEvery(votes, countCatVotes)
    
// it should have counted 3 cat votes
console.log(catVotes)

It should increment catVotes each time it finds a cat in the array, and catVotes should be 3.

Test #3

If we use it like this:

const emails = [
  { message: "Hello", read: true },
  { message: "Read Me", read: false },
  { message: "Spam", read: false },
  { message: "Forward", read: false },
  { message: "Shipped", read: true },
]
const markRead = (email) => email.read = true;
forEvery(emails, markRead)
    
// it should have marked all the emails as read
console.log(emails)

It should set each email’s read property to true.

Leave a Reply

Your email address will not be published. Required fields are marked *