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

Does anyone know why this keeps returning an empty array?

This getIndexNames function keeps returning an empty array, I cant figure out why?

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



function getIndexNames(arrayName){

        var names=[];

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

    return names
}

2 Answers

Hi again,

I typed it out and tested it in the console and got it to work.. If you try

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, 'Stoner')
];

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

I need to learn how to post code... Sorry for that mess, haha :)

Thanks!! yeah that's working :) I seen now I put >= instead of <=. I'm confused though I think <= is a comparison operator that should work if < does.

dont worry about the ```javascript I have the same problem before just wouldnt work for me lol

var animals=[ new Animal(4, 'spike'), new Animal(2, 'jack'), new Animal(8, 'Penelope'), new Animal(10, 'Stoner') ];

You can't assign variables inside of an array, and you don't have to put a comma after the last element of the array. I think it should work if you use the array I typed out above, but I haven't tested it.

Also, when looping over an array the following syntax looks better, I think: i < arrayName.length

thanks, I see thats not needed by arrays now lol still not working though for some reason.