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";

Upvotes: 3

Views: 110

Answers (4)

Khant
Khant

Reputation: 1122

Array Start with 0. Length Start with 1.

let say i want the last element from contact array

let contact = ['mo','so','do'];
console.log(contact[length])

It won't show a console. Y ? Because To get a last array. You always need to -1 from the array.length

Upvotes: 1

JMP
JMP

Reputation: 4467

The two loops have different ranges.

If contacts.length had equalled 4, then i would have taken on these values:

console.log('ascending loop');
for (var i = 0; i < 4; i++) {console.log(i);}
console.log('descending loop');
for (var i = 4; i > 0; i--) {console.log(i);}

Upvotes: 1

dahan raz
dahan raz

Reputation: 392

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

Upvotes: 1

Haru
Haru

Reputation: 145

On the answer, the for counter go like 0 ... n, and on your for loop, the counter goes like n ... 1.

So, on your code, the index never is 0

Upvotes: 0

Related Questions