Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between two loops

The code below is the correct, working solution to an exercise I had to work out. I am wondering why my solution did not work.

The only difference I had was this line:

for (var i = contacts.length; i > 0; i--) {

Why it did not do the same just reversed direction?

for (var i = 0; i < contacts.length; i++) {
    if (contacts[i].firstName == name){
        if (contacts[i].hasOwnProperty(prop)){
            return contacts[i][prop];
        } else{
            return "No such property";
        }
    }
}
return "No such contact";
like image 675
Mészáros Zoltán Avatar asked May 15 '26 15:05

Mészáros Zoltán


1 Answers

There are multiple problems in your code.

  • the first problem is that you start i = contacts.length and as you know there is no element in the array at the array length position because arrays go from 0 to array.length-1.
    the solution for that problem is var i = contacts.length - 1.
  • the second problem is that i never goes to zero because your stop condition is i > 0 then you never reach the first element of the array.
    the solution is changing the stop condition to i >= 0
like image 98
dahan raz Avatar answered May 17 '26 05:05

dahan raz