Method call doesn't do what it says it should


#1

Hi all

The instructions for this exercise say this:

“Replace the word method in the first method call with a method that will do something to each of the values in the array and return undefined.”

Referring to this code:

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

let nums = [1, 50, 75, 200, 350, 525, 1000];

// Choose a method that will return undefined
cities.method(city => console.log('Have you visited ’ + city + ‘?’));

The solution is to use cities.forEach - this doesn’t return undefined at all, it logs the names of the cities. How is this a correct solution?


#2

return is different from logging to console.


#3

Ok, so where does return go in this example?


#4

looking at the documentation:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

we see that forEach returns undefined by default, so you don’t have to insert return anywhere in your code


#5

Ah I see, so if I enter

return cities.forEach()

… on a new line, this returns an error as cities.forEach() needs arguments, and that’s what the instructions refer to?

If so, the wording of this exercise seems a little vague to me.

Thanks for your response!


#6

Replace the word method in the first method call with a method that will do something to each of the values in the array

so we have this:

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

then we replace the word method with the actual method we want to use, in this case forEach:


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

then the second part of the instructions is:

and return undefined.

forEach returns undefined by default (you can see this in documentation), so its all good


#7

I’m on the summary where it states

.forEach() is used to execute the same code on every element in an array but does not change the array and returns undefined.

This makes more sense now, but I think the wording of this could be changed to avoid confusing people - I was expecting it to factor into my code.


#8

Important part of programming is understanding the requirements and instructions, the earlier you learn this the better.