Choose the right iterator


There’s something I’m not understanding…

In Java Script: Iterators 6/7:

let cities = ['Nashville', 'Charlotte', 'Asheville', 'Austin', 'Boulder'];

//  Choose a method that will return undefined

cities.forEach(city => console.log('Have you visited ' + city + '?'));

I know the method .forEach is the correct answer, but why? How does it return undefined? I don’t seem to be able to observe it happening or understand why it would happen. if you call the ‘cities’ array after your answer it’s still the same array, nothing is undefined; the code in the lesson itself successfully prints to the console the text of each ‘city’ in the ‘cities’ array, nothing is undefined. How does the method return undefined?:thinking:

I’ve read the MDN documentation and it, sure enough, says “undefined” under the “Return value” section. I find the description for why incredibly confusing-- If I spent a very long time I could probably figure it out, but considering I’ve been finding everything else quite easy to understand-- I’m thinking I must be missing something here. Is there a simple way to observe or understand how .forEach() is causing this code to return undefined?

A more clear question: if .forEach() is causing a return of undefined in the code above, what code could I add to make that return of undefined appear in the console?


A function named “add” presumably returns the sum of provided arguments

console.log(add(3, 2))  // 5


undefined simply means there is no return value from the method.

    function foo() {


    console.log(foo()):    //  undefined

The same would apply if the function or method has a return statement but no value

    function foo() {

    console.log(foo()):    //  undefined


Ahhh yes. One could say it doesn’t ‘return undefined’ but rather doesn’t return anything. I understand now thanks.


And we can reason why this iterator would not return anything, since its job is to iterate an array from end to end (.forEach() cannot be terminated).

Array.forEach( function to execute on each element in Array )

[1,1,2,3,5,8,13].forEach(x => console.log(x));

Above illustrates a clear case for no return value.

/* <-
=> undefined