Introduction to Iterators: Javascript
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 theforEachmethod on thefruitsarray..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 beundefined.
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.
numbersis an array of numbers.bigNumbersstore the return value of calling.map()onnumbers.numbers.mapiterate through each element in thenumbersarray and pass the element into the callback function.return number * 10is the code executed upon each element in the array. This saves each value from thenumbersarray, multiplied by10, 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']
wordsis 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 thewordsarray will be passed to this function as an argument. word.length < 6;is the condition in the callback function. Anywordfrom thewordsarray that has fewer than6characters is added to theshortWordsarray.
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
jumbledNumsis 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 thejumbledNumsarray 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 totruefor 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
numbersis an array that contains numbers.summedNumsis a variable that stores the returned value of invoking.reduce()onnumbers.numbers.reduce()calls the.reduce()method on thenumbersarray and takes in a callback function as an argument.- The callback function has two parameters,
accumulatorandcurrentValue. The value ofaccumulatorstarts off as the value of the first element in the array and thecurrentValuestarts as the second element. To see the value ofaccumulatorandcurrentValue, useconsole.log() - As
.reduce()iterates through the array, the return value of the callback function becomes theaccumulatorvalue for the next iteration,currentValuetakes 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: 117There 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 returnsundefined..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-1if 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:
