Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

brandonlind2
brandonlind2
7,823 Points

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

Arjuna Huffman
Arjuna Huffman
2,400 Points

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

Arjuna Huffman
Arjuna Huffman
2,400 Points

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

brandonlind2
brandonlind2
7,823 Points

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.

brandonlind2
brandonlind2
7,823 Points

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

Arjuna Huffman
Arjuna Huffman
2,400 Points

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.

Arjuna Huffman
Arjuna Huffman
2,400 Points

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

brandonlind2
brandonlind2
7,823 Points

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