+ 1
The forEach() method on arrays returns undefined, how do we use it without logging to the console or calling the alert function
13 Respuestas
+ 3
If wanna return an array of return element use map function instead of forEach
list.map(e => {
// Do stuff
return something;
})
+ 2
Code please
+ 1
let arr= [1,2,3];
arr.forEach(myFunction)
function myFunction(item, index, ary) {
ary[index] = item * 2;
}
console.log(arr);
+ 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.
0
Take for istance
Let arr = [1, 2, 3]
let c = arr.forEach(item => return item * 2)
alert (c)
0
I don't want it to be returned to the console nor use the alert function but returned using the return keyword.
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()
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
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.
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?
0
Yes, mostly you use the following:
document.write()
console.log()
alert()
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. 💻
0
Thank you all for your answers