Iterables & Looping Flashcards Preview

Javascript ES6 > Iterables & Looping > Flashcards

Flashcards in Iterables & Looping Deck (10)
Loading flashcards...
1
Q

What advantages do the ‘for of’ loop offer over other loops.

for (const cut of cuts) {
console.log(cut);
}

A

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

2
Q

in a ‘for of’ loop how would you skip the current iteration

A

continue

3
Q

in a ‘for of’ loop how would you stop the loop?

A

break

4
Q

How would you get the index of a ‘for of’ loop?

A

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);
}

5
Q

What can you use for of loops with?

A

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.

6
Q

how would you ‘for of’ loop through all elements and add an event listener

A
const ps = document.querySelectorAll('p');
for (const ps in parage ){ 
paragraph.addEventListener('click' function (){
    console.log(this.textContent);
});
7
Q

if you have a function that could have any number of arguments what could you use?

A

The arguments object.

  1. don’t add anything to the function parameters
  2. access ‘arguments’ from within function
8
Q

Why is the arguments array not really a true array?

A

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.

9
Q

Why must you declare a const or let in a for of loop?

A

If you don’t you’ll be overwriting the same variable every time instead of creating a variable that is scoped to that block.

10
Q

Dom collections in most browser don’t have many the methods you are you to. Correct or false?

A

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.