Array Iterators quiz

link: https://www.codecademy.com/paths/web-development/tracks/web-dev-js-arrays-loops-objects/modules/learn-javascript-iterators/projects/mini-linter

I really like how the teacher solved itens 4 and 5 of the Quiz. Amazing stuff to learn.

But I was expecting something using arrays iterators. So here are my questions:

  1. what are the alternative ways to solve itens 4 and 5 without using “for”, as used on the resolution video? Is it possible with a function or iterator? how would the code look like on these situations? I tried buiild something by myself, but I don’t have the logic and knowledge to do that alone yet.

  2. I wasnt aware of the construction for(word of storyWord). this is valid just for strings? where can I read more about it? word must be already a variable declared, right?

  3. Why, on item 7, if I use just xxxxx.join(), the output will be made of strings with a comma among then? so the result would be xxxxx.join(' ')

let repExtremely = 0;
let repLiterally = 0;
let repActually = 0;

for(word of storyWords){
  if (word === 'extremely'){
    repExtremely += 1;
  } else if (word === 'literally'){
    repLiterally += 1;
  } else if (word === 'actually') {
    repActually += 1  }
}
let sentenceCount = 0
for (word of storyWords) {
if (word[word.length - 1] === '.' || word[word.length - 1] === '!')
sentenceCount += 1;
}

Thanks in advance.

@jhonathanc

There are a number of ways to solve problems using JS. I won’t attempt to list them all here. With modern computers and fast internets speeds, readability and simplicity are often prioritised. A ‘for…of’ loop makes perfect sense here; it is simple and very easy to read.

No, a ‘for…of’ loop is compatible with a variety of iterables. In this case, “word” represents the current iterable (index or item) in the array, while “storyWord” represents the full array.

In short:

for (const each-item of my-array) {
  do something
}

Here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

The variable ‘word’ is conveniently declared inside of the parenthesis of the ‘for…of’ loop and assigned the value of each iterable element on each iteration.

The syntax is:

array.join([separator])

So, .join(' ') results with a space between each ‘word’.

1 Like

Nice, it helped me a lot. Thank you very much, @cakaragiannis

1 Like