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

What if i want to make a function out of it to be called later?

So given the array of names we should get all the names strrting with 'S' in a new array. What if i want to leave the whole code as a function to be called later when i need to get names with 'S'? The only problem i encountered is that when i call the function it gives me not only the array with the names with 'S' but also and 'undefined' afterwards. Where does that 'undefined' come from? Thanks for help

const names = ['Selma', 'Ted', 'Mike', 'Sam', 'Sharon', 'Marvin'];
    // Result: ['Selma', 'Sam', 'Sharon'];

let namesWithS = [];

function namesWithSfunction() { 
  names.forEach((name) => {
    if (name.charAt(0) === 'S') {
      namesWithS.push(name);
    }
  });
  console.log(namesWithS);
};

console.log(namesWithSfunction());

And here's what i get in the console

treehouse:~/workspace$ node iteration.js                                                                                
[ 'Selma', 'Sam', 'Sharon' ]                                                                                            
undefined                   

1 Answer

Steven Parker
Steven Parker
242,796 Points

This function does not "return" anything, so when you call it inside a "console.log", the log displays "undefined".

You can easily convert it to return the list instead of logging it internally:

  console.log(namesWithS);  // replace this line...
  return namesWithS;        // with this

Thanks so much Steven. I can't beleive i missed that. It was so obvious. Sorry, and thanks again.