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

RODRIGO MARTINEZ
RODRIGO MARTINEZ
5,912 Points

// Define a function printArrElements(someArr) that will loop through array and print all the elements of that array.

So i had the following task.

"Define a function printArrElements(someArr) that will loop through array and print all the elements of that array. Use the following array to pass it as an argument to the function you’ve just defined:"

I wrote a function that works but in the console i get 2 "undefined" after the console returns all of the elements of the array.

let ironCities = ["Amsterdam", "Barcelona", "Berlin", "Lisbon", "Madrid", "Mexico City", "Miami", "Paris", "Sao Paulo" ];

function printArrElements(someArr) {
  for (let i = 0; i <= someArr.length; i++) {
    console.log(someArr[i]);
  }
};
console.log(printArrElements(ironCities));

And i got the following result on the console:

"Amsterdam"
"Barcelona"
"Berlin"
"Lisbon"
"Madrid"
"Mexico City"
"Miami"
"Paris"
"Sao Paulo"
undefined
undefined

Why am i getting these two "undefined" in the end?

Thanks for the help

Chris Freeman
Chris Freeman
Treehouse Moderator 67,986 Points

One of your undefined is due to the loop over run. The condition should be i < someArr.length;. I'm not sure of the other.

RODRIGO MARTINEZ
RODRIGO MARTINEZ
5,912 Points

Thanks, Chris. Didn't see that one. I appreciate the help

1 Answer

Chris pointed out the first one. The second is because you are logging a function with no return statement. The default value for this is undefined.

RODRIGO MARTINEZ
RODRIGO MARTINEZ
5,912 Points

Hello Kris. I consoled logged it directly as when i tried "return someArr[i]". The code would stop as expected, without looping through the rest of the array. So i was getting only the first element of the array. How can i return so i get all of the elements. What kind of sintax issue am i having? Thanks again for helping out..