Introduction To Iterators
Introduction To Iterators
Introduction to Iterators
Imagine you had a grocery list and you wanted to know what each item on the list was.
You'd have to scan through each row and check for the item. This common task is
similar to what we have to do when we want to iterate over, or loop through, an array.
One tool at our disposal is the for loop. However, we also have access to built-in array
methods which make looping easier.
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.
In this lesson, you will learn the syntax for these methods, their return values, how to use
the documentation to understand them, and how to choose the right iterator method
for a given task.
Instruction
artists.forEach(artist => {
console.log(artist + ' is one of my favorite artists.');
});
console.log(squareNumbers);
console.log(onlyNumbers);
Inspect the code in main.js. Notice the different methods being called on the arrays:
.forEach()
.map()
.filter()
The first iteration method that we're going to learn is .forEach(). Aptly
named, .forEach() will execute the same code for each element of an array.
The code above will log a nicely formatted list of the groceries to the console. Let's
explore the syntax of invoking .forEach().
groceries.forEach(groceryItem =>
console.log(groceryItem));
function printGrocery(element) {
console.log(element);
}
groceries.forEach(printGrocery);
The above example uses a function declaration but you can also use a function
expression or arrow function as well.
All three code snippets do the same thing. In each array iteration method, we can use
any of the three examples to supply a callback function as an argument to the iterator.
It's good to be aware of the different ways to pass in callback functions as arguments in
iterators because developers have different stylistic preferences. Nonetheless, due to the
strong adoption of ES6, we will be using arrow function syntax in the later exercises.
Instruction
1. Iterate over the fruits array to log I want to eat aplus the name of each
fruit to the console. For example, I want to eat a mango.
You may use any form of callback you prefer.
Hint: Use dot notation to access the .forEach() method on the array and use a
set of parentheses to call the method.
[1, 2, 3, 4].forEach()
[1, 2, 3, 4].forEach(function(element){
console.log(`Printing ${element} to the console!`)
})
The second iterator we're going to cover is .map(). When .map() is called on an array,
it takes an argument of a callback function and returns a new array! Take a look at an
example of calling .map():
Notice that the elements in numbers were not altered and bigNumbers is a new array.
Instruction
Solution:
Solution:
console.log(smallNumbers)
The .filter() Method
Instruction
console.log(lessThanTen); // Output: 3
console.log(jumbledNums[3]); // Output: 5
Great, the element in index 3 is the number 5. This makes sense since 5 is the first
element that is less than 10.
If there isn't a single element in the array that satisfies the condition in the callback,
then .findIndex() will return -1.
console.log(greaterThan1000); // Output: -1
Instruction
console.log(summedNums) // Output: 17
Here are the values of accumulator and currentValue as we iterate through
the numbers array:
Here's an updated chart that accounts for the second argument of 100:
Instruction
You'll also see a TypeError: undefined is not a function but we'll fix that
after we add our callback function in the next step!
Hint: To call .reduce() on an array, use dot notation:
const sampleArr = [10, 10, 10];
const reduceExample = sampleArr.reduce();
2. Provide .reduce with an argument of a callback function. The callback function
has two parameters. The first parameter is accumulator and the second
parameter is currentValue. Use either a function expression or an arrow
function.
Hint: The syntax for a function expression looks like:
const reduceExample = sampleArr.reduce(function(accumulator,
currentValue) {
});
});
3. To check the value being used as we iterate through the array, add three
statements to the function body of the callback:
Or
const newSum = newNumbers.reduce((accumulator, currentValue) => {
console.log('The value of accumulator: ', accumulator);
console.log('The value of currentValue: ', currentValue);
return accumulator + currentValue;
})
4. Log the value of newSum to the console to see the return value of
calling .reduce() on newNumbers.
5. While we have this code set up, let's also check what happens if you add a
second argument to .reduce(). The second argument acts as an initial value for
the accumulator.
Add a second argument of 10 to .reduce().
Hint: Make sure you're adding a second argument to .reduce()and not another
argument to the callback function.
Iterator Documentation
There are many additional built-in array methods, a complete list of which is on
the MDN's Array iteration methods page.
1. A short definition.
2. A block with the correct syntax for using the method.
3. A list of parameters the method accepts or requires.
4. The return value of the function.
5. An extended description.
6. Examples of the method's use.
7. Other additional information.
In the instructions below, there are some errors in the code. Use the documentation for
a given method to determine the error or fill in a blank to make the code run correctly.
Instruction
console.log(words.some(() => {
return word.length < 6;
}));
// Make sure to uncomment the code below and fix the incorrect code
before running it
1. In the code editor, there is an array called words. We want to create a new array
of interesting words. The first thing we want to do is check if there are words that
are fewer than 6 characters long. There is something missing in
the words.some() method call. Fix this method so that true is printed to the
console.
For more information browse MDN's documentation on .some() .
Hint: In the function body of .some() you should return true if the element in
the words array has less than 6 characters. If you run the code, you'll see that
there's a reference error because the argument, word, wasn't passed into the
callback function.
2. The .some() method returned true, which means there are some words in the
array that are shorter than six characters. Use the .filter() method to save any
words longer than 5 characters to a new variable called interestingWords,
declared with const.
We've used .filter() in a previous exercise, but, for more information
browse MDN's documentation on .filter() .
Solution:
// Use filter to create a new array
const interestingWords = words.filter(function(wordFiler) {
return wordFiler.length > 5;
})
Make sure to uncomment (delete the // before) the last line of the program
before you run the code.
There are many iteration methods you can choose. In addition to learning the correct
syntax for the use of iteration methods, it is also important to learn how to choose the
correct method for different scenarios. The exercises below will give you the opportunity
to do just that!
You'll see errors pop up in the terminal as you work through this exercise, but by the
end the errors will be gone!
Instruction
console.log(word)
1. Replace the word method in the first method call with a method that will do
something to each of the values in the array and return undefined.
Hint: Think about what iteration method will return undefined.
Solution: .forEach()
2. In the second method call, replace the word methodwith a method that will
return a new array with only those elements longer than 7 characters.
Solution: .filter()
3. In the third method call, replace the word method with a method that take an
array that contains multiple values and returns a single value.
Hint: This iteration method will take the elements of an array and return a single
value.
Solution: .reduce()
4. In the fourth method call, replace the word methodwith a method that will return
a new array of numbers returned from the function.
Hint: What method would create new array that will have the same length of the
original array?
Solution: .map()
5. In the fifth method call, replace the word method with a method that will return a
boolean value.
Hint: There are two iteration methods that you learned about in this lesson that
would return a boolean value, true or false.
Solution: .some()
Review
Awesome job on clearing the iterators lesson! You have learned a number of useful
methods in this lesson as well as how to use the JavaScript documentation from the
Mozilla Developer Network to discover and understand additional methods. Let's
review!
.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 which 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 takes a callback function that can be pre-defined, or a
function expression, or an arrow function.
You can visit the Mozilla Developer Network to learn more about iterator
methods (and all other parts of JavaScript!).
Instruction