5/8 Nested For Loops


#1

Nested For Loops, specifically step 3 is being non-compliant. I think!

When my Array and For Loop run, I get a Reference Error stating that ‘myPlacesIndex is not defined’. I’m hoping I am just making a simple mistake, but for the life of me I don’t see it. I’d like to solve this one, and not simply ‘Get Code’ blurg.



let myPlaces = ['Colorado', 'California', 'Iceland'];
let friendPlaces = ['Colorado', 'Portugal', 'Brazil'];

for (let myPlacesIndex = 0; myPlacesIndex < myPlaces.length; myPlacesIndex++); {
  console.log(myPlaces[myPlacesIndex]);
}



#2

@tinagekicks you have a syntax error after the for conditional there is an ;


#3

Hey thanks @tommygebru that was totally the case! Do you know any of the rationale there? I’m just surprised it threw such a fit over that.


#4

The semi-colon is an end of statement token so JavaScript stops parsing and treats the block that follows as a new statement. Blocks {...} are valid but merge into normal flow, so the statement inside the block will execute, but the loop will not.

Edit

Actually, the statement will not execute since the let keyword scopes the variable to the loop.

ReferenceError: myPlacesIndex is not defined
at eval:5:3

Just for the practice, let’s declare the variable before the loop so it exists outside of the loop block.

let myPlacesIndex;
for (myPlacesIndex = 0; myPlacesIndex < myPlaces.length; myPlacesIndex++); {
  console.log(myPlaces[myPlacesIndex]);
}
Native Browser JavaScript
 > 
undefined
=> undefined
 >

Now let’s give it a value…

let myPlaces = ['Colorado', 'California', 'Iceland'];
let friendPlaces = ['Colorado', 'Portugal', 'Brazil'];

let myPlacesIndex = 0;
for (; myPlacesIndex < myPlaces.length; myPlacesIndex++); {
  console.log(myPlaces[myPlacesIndex]);
}
Native Browser JavaScript
 > 
undefined
=> undefined
 >

Why still undefined? Because the loop does run, enough to increment the index to 3. There is no myPlaces[3].

let myPlacesIndex = 0;
for (; myPlacesIndex < myPlaces.length; myPlacesIndex++); 
{
  console.log(myPlaces[myPlacesIndex - 1]);
}
Native Browser JavaScript
 > 
Iceland
=> undefined
 >

#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.