Loops & Iteration Flashcards
When looping through arrays, why is a for…of loop preferred over a standard for loop?
A for…of will loop over the array once without the need for setting increments or conditionals
What is the full syntax of the forEach method?
The syntax of the forEach method, which is found on arrays:
arrayName.forEach((currentValue, index, array) ={
codeBlock of loop
})
Does the forEach method for arrays take a callback?
Yes, the forEach method takes a callback.
What are the three parameters for a forEach callback function?
currentValue, index, array
What is the most common way we would see a forEach method?
Looping over an array when we are concerned with the currentValue only.
arrayName.forEach((currentValue) => {doSomething with currentValue})
Which is faster, a forEach method call or a for…of loop?
The for…of loop is faster.
How can we refer to a variable name when looking at iteration syntax?
The variable name can also be called the “Identifier”
What is the returned value for a .forEach method call?
It is always undefined, we need to do something with the function product in the callback itself
How does the .forEach method work?
.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.
Are .forEach and for…of iteration methods equivilent?
No, .forEach does not work well with Async/Await and some edge cases. for…of iteration can make it difficult to get the index value and can’t be chained.
What is the difference between .map and .forEach?
.map creates a new array with the results of the callback function provided.
How is the .filter method used?
Use the .filter method to iterate over an array and then create a new array with elements that return true to the callback function
Does the .filter method create a new array?
Yes, it creates a new array out of elements that return true in the callback function.
What does the method .findIndex return?
It will return the index of the first element in an array that evaluates to true in the callback function.
What will .findIndex return if no elements evaluate to true in the callback function?
.findIndex will return -1 if no elements evaluate to true in the callback function.