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

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 68,457 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..