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 trialbrandonlind2
7,823 PointsWhy is the < comparison operator working, but the <= comparison operator creating an error?
/***I know < and <= are different but they're similar and from my understanding
if one works the other should also work, I'm confused as to why the bottom function isn't working?
the bottom code isn't working but if I replace the <=with < it works?***/
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
jcorum
71,830 PointsArrays are zero-based. That means that the the first element has an index of 0.
for(var i=0; i <= arrayName.length; i++){
Since i starts at 0, it has to stop at 1 less than the length of the array, as the last index number for an array with 10 elements is 9.
brandonlind2
7,823 Pointsbrandonlind2
7,823 PointsThanks I didn't think about that, however I'm getting "Uncaught TypeError: Cannot read property 'name' of undefined(…)"