For Loops, Backwards


#1

Hello,

Can someone please tell what is wrong to my code, I mean it’s printing the way it should be but the system cannot accept my code.

let vacationSpots = ['boracay','cebu','palawan'];

for( let vacationSpotIndex = vacationSpots.length; vacationSpotIndex >= 0; vacationSpotIndex --    ){
        console.log('I would love to visit' + ' ' +  vacationSpots[vacationSpotIndex]);
};

#2

Please post a link to the exercise, as well as any error messages. Thanks.


#3

Here is the link
https://www.codecademy.com/courses/learn-javascript-loops/lessons/loops/exercises/for-loop-ii?action=lesson_resume&course_redirect=introduction-to-javascript

The error says “Did you log the vacation spot to the console?”


#4

Is there any error in console window?

I’m guessing you might be getting an index out of range error? There is no element,

vacationSpots[vacationSpots.length]

#5

I tried it too but it does not work either. I have been stucked from here since yesterday and cant figure out what could be the problem.


#6

One way to deal with this…

const arr = [1,2,3,4,5,6,7,8,9]

for (let i = arr.length; i > 0; i--) {
    console.log(arr[i - 1]);
}

Note the conditional. > 0. We do not want it to equal zero since we are subtracting in the subscript. When i is 1, the index we access will be [0].


#7

Thank you for the help! let me try that one out…


#8

Work out the mechanics, then substitute in the expected variable names.


#9

I like this example much better than the example that the “for Loops Backwards” lesson suggests (Lesson page 4/8). Is there any way you could change the example ? This is much easier to read and understand.


#10

In some world that I don’t completely understand, long, verbose variable names are supposed to be self-documenting the code. Maybe that is true, though like yourself, I prefer to think through the code and gain my own understanding of it. We can still self-document (with appropriate naming) without exaggerating the obvious, in my view.


#11

Hi!
Do you actually have a space between your index variable and the unary --? Or is that just the formatting being goofy? If there is a space, try taking it out. Unaries don’t take space on each side, unlike the other operators.

“… vacationSpotIndex – )”

Hope it works out!


#12

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