Home > Back-end >  Why do an unexpected token "return" with forEach?
Why do an unexpected token "return" with forEach?

Time:12-03

Why doesn't ara return the unxpected token error, instead of 23 added to each value in the array?

        var aras = [1,2,3,4,5]
        let ara = aras.forEach(item => item   23);

CodePudding user response:

forEach does return undefined. to return new array use map.

var aras = [1,2,3,4,5]
let ara = aras.map(item => item   23);

CodePudding user response:

Array.forEach doesnot return any value. So the value for ara in your statement will be undefined.

Array.forEach just loops through each element in an array, and perform an action. Here your action is item 23, but it doesnot update anywhere.

If you want to genereate a new array from an existing one by making some changes to each element in the array, use Array.map

var aras = [1,2,3,4,5]
let ara = aras.map(item => item   23);
console.log(ara);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related