Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

can someone explain why this comparison operator isnt working?

/***the comparison operator in the for loop works perfectly if its < but it stops working
 if I change it to <=, and I cant figure out why***/

function Animal(age, name){ 
    this.age=age; 
    this.name=name; 
    } 
var animals=[
     new Animal(4, 'spike'),
     new Animal(2, 'jack'), 
     new Animal(8, 'Penelope'), 
     new Animal(10, 'speedy')
];

function getIndexNames(arrayName){

    var names=[];

for(var i=0; i <= arrayName.length; i++){
   names.push(arrayName[i].name);
    }

return names;
}

var returnedArr = getIndexNames(animals);

console.log(returnedArr);

1 Answer

It's because arrays are zero-based.

The last entry in your animals array is 'speedy', at index 3. The length of your array is 4.

When you use the < operator, the for loop will loop over indexes 0,1,2,3 but when you use <=, it will loop over 0,1,2,3,4. There is nothing at index 4 of your array so you get an error when you try access the name property of your non-existing object.

(reposted here because I realised I'd posted in the wrong field)

Thanks!!