Introduction to Iterators: Javascript

Henna Singh
5 min readApr 3, 2022

#BuildTogether Day 56/00

Today was a long day that involved traveling to a different country ;) I think I have always liked to travel to new places. And it’s super amazing if you get lucky to meet new people on your journey 😍 This time I totally was and spent a good deal of the afternoon exploring the place ;)

Iterators

The built-in JavaScript array methods that help us iterate are called iteration methods, at times referred to as iterators. Iterators are methods called on arrays to manipulate elements and return values.

The .forEach() Method

As its named, .forEach() method will execute the same code for each element of an array

const fruits = ['mango', 'papaya', 'pineapple', 'apple'];// Iterate over fruits belowfruits.forEach(fruit => {console.log('I want to eat a ' + fruit);})
  • fruots.forEach() calls the forEach method on the fruits array.
  • .forEach() takes an argument of a callback function (a callback function is a function passed as an argument into another function).
  • .forEach() loops through the array and executes the callback function for each element. During each execution, the current element is passed as an argument to the callback function.
  • The return value for .forEach() will always be undefined.

The function can also be defined beforehand to be used as a callback function

function printFruits(element){
console.log(element);
}

fruits.forEach(printFruits);

function declaration, expression or arrow functions can be used.

The .map() Method

When .map() is called on an array, it takes an argument of a callback function and returns a new array!

const numbers = [1, 2, 3, 4, 5]; 

const bigNumbers = numbers.map(number => {
return number * 10;
});
console.log(bigNumbers); // Output: [10, 20, 30, 40, 50]

The major difference between .forEach() and .map() is that .map()returns a new array.

  • numbers is an array of numbers.
  • bigNumbers store the return value of calling .map() on numbers.
  • numbers.map iterate through each element in the numbers array and pass the element into the callback function.
  • return number * 10 is the code executed upon each element in the array. This saves each value from the numbers array, multiplied by 10, to a new array.

The .filter() Method

.filter() returns an array of elements after filtering out certain elements from the original array. The callback function for the .filter() method returns true or false depending on the element that is passed to it. The elements that cause the callback function to return true are added to the new array.

const words = ['chair', 'music', 'pillow', 'brick', 'pen', 'door']; 

const shortWords = words.filter(word => {
return word.length < 6;
});
console.log(shortWords); // Output: ['chair', 'music', 'brick', 'pen', 'door']
  • words is an array that contains string elements.
  • const shortWords = declares a new variable that stores the returned array from invoking .filter().
  • The callback function is an arrow function that has a single parameter, word. Each element in the words array will be passed to this function as an argument.
  • word.length < 6; is the condition in the callback function. Any word from the words array that has fewer than 6 characters is added to the shortWords array.

The .findIndex() Method

Calling .findIndex() on an array returns the index of the first element that evaluates to true in the callback function.

const jumbledNums = [123, 25, 78, 5, 9]; 

const lessThanTen = jumbledNums.findIndex(num => {
return num < 10;
});
console.log(lessThanTen); // Output: 3
console.log(jumbledNums[3]); // Output: 5
  • jumbledNums is an array that contains number elements.
  • const lessThanTen = declares a new variable that stores the returned index number from invoking .findIndex().
  • The callback function is an arrow function that has a single parameter, num. Each element in the jumbledNums array is passed to this function as an argument.
  • num < 10; is the condition that elements are checked against. .findIndex() will return the index of the first element which evaluates to true for that condition.

If there isn’t a single element in the array that satisfies the condition in the callback, then .findIndex() will return -1.

The .reduce() Method

The .reduce() method returns a single value after iterating through the elements of an array, thereby reducing the array.

const numbers = [1, 2, 4, 10];

const summedNums = numbers.reduce((accumulator, currentValue) => {
console.log('The value of accumulator: ', accumulator);console.log('The value of currentValue: ', currentValue);return accumulator + currentValue
})

console.log(summedNums) // Output: 17
  • numbers is an array that contains numbers.
  • summedNums is a variable that stores the returned value of invoking .reduce() on numbers.
  • numbers.reduce() calls the .reduce() method on the numbers array and takes in a callback function as an argument.
  • The callback function has two parameters, accumulator and currentValue. The value of accumulator starts off as the value of the first element in the array and the currentValue starts as the second element. To see the value of accumulator and currentValue , use console.log()
  • As .reduce() iterates through the array, the return value of the callback function becomes the accumulator value for the next iteration, currentValue takes on the value of the current element in the looping process.

The .reduce() method can also take an optional second parameter to set an initial value for accumulator .

const numbers = [1, 2, 4, 10];

const summedNums = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue
}, 100) // <- Second argument for .reduce()

console.log(summedNums); // Output: 117

There are many additional built-in array methods, a complete list of which is on the MDN’s Array iteration methods page.

Some more examples are in the below code:

In a Nutshell

  • .forEach() is used to execute the same code on every element in an array but does not change the array and returns undefined.
  • .map() executes the same code on every element in an array and returns a new array with the updated elements.
  • .filter() checks every element in an array to see if it meets certain criteria and returns a new array with the elements that return truthy for the criteria.
  • .findIndex() returns the index of the first element of an array that satisfies a condition in the callback function. It returns -1 if none of the elements in the array satisfies the condition.
  • .reduce() iterates through an array and takes the values of the elements and returns a single value.
  • All iterator methods take a callback function, which can be a pre-defined function, a function expression, or an arrow function.
  • Visit the Mozilla Developer Network for more iterator methods.

That is all for today. If you fancy reading my 100 Days Journey, please feel free to drop by:

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Henna Singh
Henna Singh

Written by Henna Singh

Technical Speaker and an aspiring writer with avid addiction to gadgets, meet-up groups, and paper crafts. Currently doing Full Stack Diploma at Code Institute

No responses yet

Write a response