Iterables & Looping Flashcards
What advantages do the ‘for of’ loop offer over other loops.
for (const cut of cuts) {
console.log(cut);
}
If the prototype has been altered on the data we are looping through or a property has been add to an array. ‘for each’ and ‘for in’ can loop through this info too which is not an ideal behaviour.
for of saves this issues and also allows:
in ‘for of’ loops you can:
continue - skip to the next iteration
break - stop the loop entirely
in a ‘for of’ loop how would you skip the current iteration
continue
in a ‘for of’ loop how would you stop the loop?
break
How would you get the index of a ‘for of’ loop?
If we iterate over the array iterator instead of the array itself we can destructure what it returns into its own variables to get our index and its value in separate variables:
for (const [i, cut] of cuts.entries() ) {
console.log(cut, i);
}
What can you use for of loops with?
Anything that is iterable so it doesn’t have to be an array. e.g dom collection, arguments, string, array or set.
You can’t use them with objects.
how would you ‘for of’ loop through all elements and add an event listener
const ps = document.querySelectorAll('p'); for (const ps in parage ){ paragraph.addEventListener('click' function (){ console.log(this.textContent); });
if you have a function that could have any number of arguments what could you use?
The arguments object.
- don’t add anything to the function parameters
- access ‘arguments’ from within function
Why is the arguments array not really a true array?
The prototype is an object while true arrays have an array of methods on the prototype.
It is essentially a list with out any methods.
No need to loop over them.
Why must you declare a const or let in a for of loop?
If you don’t you’ll be overwriting the same variable every time instead of creating a variable that is scoped to that block.
Dom collections in most browser don’t have many the methods you are you to. Correct or false?
Correct.
They will eventually but for now it’s something to be aware of.
You can still loop through these lists with ‘for of’ loops.