Why is .forEach() undefined? How do we make .forEach() defined? do we use return in the function?
Hi, so you don’t necessarily need to use return in the function, you just have to define a variable first then write your method. Here is an example :
As you can see here a new variable has been defined and you have a console.log() method that will execute 5 times on, once on each element.
Hope that helps.
Happy coding !
thank you! just wondering, under what conditions are forEach() functions undefined?
this returns undefined. why is this so?
Well I believe that your console.log() method should be inside your function like so :
This is the syntax, well you could also create a new variable which contains a function then use console.log() on your function with an argument to get the result.
The output of a
.forEach() will be always undefined (see the MDN documentation on it). It’s closer to a
for loop than a regular function in that sense.
If you want to do something to every element of an array and get an array out of it, you probably want to use
.map() (.map MDN doc).
You can see in the code below some of the different behaviors.
First in the log is the
console.log(e**2); in the
.forEach loging the squares of the elements of
newArr1, being the output of the
arr.forEach( ... ), is undefined.
newArr2, is initialized ahead of time and ammended during the
arr.forEach( ... ), so it is well defined with the squares of
newArr3 shows how you can get the same functionality as with
arr.forEach( ... ) and the predefined
newArr2, but with much more efficiency by using
Also, you can uncomment the
return e++; on line 7 and see that it doesn’t make a difference—
forEach just isn’t set up to return anything.
You could also do something like in the code below if you want to use
forEach to revise the array in question directly.
Note that this lets you edit the array even though it is initialized with
const (if you add, say,
arr = [1, 2]; at the end of the code, it will complain:
TypeError: Assignment to constant variable.).