+ 1

The forEach() method on arrays returns undefined, how do we use it without logging to the console or calling the alert function

11th Jan 2022, 7:25 PM
JUSTIN KPAKPA
JUSTIN KPAKPA - avatar
13 ответов
+ 3
If wanna return an array of return element use map function instead of forEach list.map(e => { // Do stuff return something; })
13th Jan 2022, 3:20 AM
Kelvin Paul
Kelvin Paul - avatar
+ 2
Code please
11th Jan 2022, 7:31 PM
Shadoff
Shadoff - avatar
+ 1
let arr= [1,2,3]; arr.forEach(myFunction) function myFunction(item, index, ary) { ary[index] = item * 2; } console.log(arr);
11th Jan 2022, 7:54 PM
Shadoff
Shadoff - avatar
+ 1
It is because unlike map() and filter(), forEach() is not meant to return anything. It is used to basically read the content of the array. If all you want to do is item*2 then map() is more suitable.
11th Jan 2022, 8:22 PM
Avinesh
Avinesh - avatar
0
Take for istance Let arr = [1, 2, 3] let c = arr.forEach(item => return item * 2) alert (c)
11th Jan 2022, 7:35 PM
JUSTIN KPAKPA
JUSTIN KPAKPA - avatar
0
I don't want it to be returned to the console nor use the alert function but returned using the return keyword.
11th Jan 2022, 7:56 PM
JUSTIN KPAKPA
JUSTIN KPAKPA - avatar
0
According to the specifications it returns undefined. But you will be able to see the transformed values when you use the alert function or the console.log()
11th Jan 2022, 7:58 PM
JUSTIN KPAKPA
JUSTIN KPAKPA - avatar
0
if forEach() is used for iteration over an array, you have to visually seen the values looped over. Am I right? just as the same way of using for..of
11th Jan 2022, 8:26 PM
JUSTIN KPAKPA
JUSTIN KPAKPA - avatar
0
Yes you can say that, the difference is that it takes a callback function and for..of doesn't. It's just a fancier way of iterating.
11th Jan 2022, 8:33 PM
Avinesh
Avinesh - avatar
0
Consider this let arr = [7, 9, 0]; arr.forEach(item => return item * 2); My main concern is that the use of the return statement is undefined. I could have used alert or console.log() function to output the result. But what I really what to know is that is there a no around code to display the results without using alert or console.log?
11th Jan 2022, 8:43 PM
JUSTIN KPAKPA
JUSTIN KPAKPA - avatar
0
Yes, mostly you use the following: document.write() console.log() alert()
12th Jan 2022, 5:39 AM
Avinesh
Avinesh - avatar
0
let arr= [7, 9, 0]; arr. forEach(item =>return item * 5); My main concern is that the use of return statement is financial and defined.। Not used the console.log() function to output the result. 💻
12th Jan 2022, 11:16 AM
Shubham Bhatia
Shubham Bhatia - avatar
0
Thank you all for your answers
13th Jan 2022, 7:20 AM
JUSTIN KPAKPA
JUSTIN KPAKPA - avatar