.forEach()

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 :

const age = [28, 69, 11, 32, 16]; age.forEach(age => { console.log(age); });

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?

for example:

let numbers = [3.14, 2.58, 6.39] console.log(numbers.forEach(numbers => numbers + 1))

this returns undefined. why is this so?

Well I believe that your console.log() method should be inside your function like so :

let numbers = [3.14, 2.58, 6.39] numbers.forEach(numbers => { console.log(numbers + 1); });

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.

const arr = [1, 2, 3, 4, 5]; let newArr2 = []; let newArr1 = arr.forEach(e => { console.log(e**2); newArr2.push(e**2); // return e++; // this isn't going to make a difference }); let newArr3 = arr.map( e => e**2 ); console.log(`newArr1 is: ${newArr1}`); console.log(`newArr2 is: ${newArr2}`); console.log(`newArr3 is: ${newArr3}`);

First in the log is the console.log(e**2); in the .forEach loging the squares of the elements of arr.

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 arr.

newArr3 shows how you can get the same functionality as with arr.forEach( ... ) and the predefined newArr2, but with much more efficiency by using .map() .

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.

const arr = [1, 2, 3, 4, 5]; console.log(`arr is: ${arr}`) arr.forEach( (e,i) => { arr[i] = e**2; }); console.log(`arr is now: ${arr}`)

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.).

1 Like