4. for loop backwards. Remember the Occam's Razor?


#1


https://www.codecademy.com/courses/learn-javascript/lessons/loops/exercises/for-loop-ii?action=lesson_resume&link_content_target=interstitial_lesson


Why to complicate the things? We could use simpler solutions. I made out a right code, but they still saying that I am wrong: "Did you make the start condition of the for loop var i = vacationSpots.length?" My code runs backwards at a console log all right, however they tell me that I was wrong.


var vacationSpots = ['Aqtau', 'Burabai', 'Alakol'];

for (var i = 2; i >= 0; i--) {
  console.log('I like to pay a visit to ' + vacationSpots[i]);
}


#2

Why to complicate the things?

suppose you dont know how many elements there are?then what'll you do?
sometimes it's very useful :slight_smile:

so you should do what instruction tells you.


#3

Using var i = vacationSpots.length is better (and it is a good practice). Just remove one element from an array and don't change for() loop condition.

When you have var i = 2; you always need to keep in mind if your array was changed you need change this condition. var i = vacationSpots.length delete this behavior. So change var i = 2; to var i = vacationSpots.length, after that add or remove few elements from an array.

Starting to make sense?


#4

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