Mini Linter step 4

I have never seen or learned yet to write a for loop as it is shown at the walkthrough video for step 4 - for (word of storyWords)

**for(word of storyWords) {**

  if(word === 'really') {
    reallyCount += 1;
   if(word === 'very') {
    veryCount += 1;
  if(word === 'basically') {
    basicallyCount += 1;

[walkthrough video ( step 4)](```
What does this method called and where can I look up to learn more about it?
1 Like

Previous to ECMA2015, we could only iterate over indices of arrays…

for (let i = 0; i < array.length; i++) {
    // access item in array by index

There was a misconception among new developers that it was okay to use the in operator, but they would eventually learn this is not okay, and should never go into production code.

for (let key in object) {
    // access value with key
    console.log(`${key}: ${object[key]}`);

Now we have a useful operator for accessing the items directly in an array, without using their index.

for (let item of array) {
    // access item in array directly

Just as we wouldn’t use in to access an array item, we would not use of to access an object key.


Hi! :wave:

I know this thread is a little old, but I’m hoping someone can answer a quick question on it! :pray:

When reading the MDN docs on for…of loops, I can see the syntax is as follows;

for (variable of iterable) {

- In reference specifically to variable in the code above, the MDN docs state;

On each iteration a value of a different property is assigned to variable. variable may be declared with const , let , or var .

From the example video linked to here by @uzikim1 :

I have quoted the developer’s code from the video below:

for (word of storyWords) {
  if (word === "really") {
    reallyCount += 1
  } if (word === "very") {
    veryCount += 1
  } if (word === "basically" ) {
    basicallyCount += 1

The one thing I am trying to work out, is why he has not declared the variable with const , let , or var - I’m certainly not suggesting this is wrong, but I’m simply to trying to understand why it is like this - is there a specific reason why const , let , or var has been omitted?

Thanks in advance!

In this particular instance, and assuming the loop is not inside a function, word will be global. If there is another variable in the same scope with the same name, the one above will overwrite it.

Using let will give the variable block scope, so no conflict will occur, but it may not matter, here. This linter is a top down program, as I recall, and word is very likely used all the way through in various situations. Any previous value will be unimportant.

While it is good practice to keep a close watch on scope, it’s not something we need to carve in stone., especially when working in global scope, only. Once we get into functions, then we need to be diligent at declaring scope so as not to pollute or conflict with the global scope.