Loop through array of values with Arrow Function

JavascriptEcmascript 6

Javascript Problem Overview


Lets say I have:

var someValues = [1, 'abc', 3, 'sss'];

How can I use an arrow function to loop through each and perform an operation on each value?

Javascript Solutions


Solution 1 - Javascript

In short:

someValues.forEach((element) => {
    console.log(element);
});

If you care about index, then second parameter can be passed to receive the index of current element:

someValues.forEach((element, index) => {
    console.log(`Current index: ${index}`);
    console.log(element);
});

> Refer here to know more about Array of ES6: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

Solution 2 - Javascript

One statement can be written as such:

someValues.forEach(x => console.log(x));

or multiple statements can be enclosed in {} like this:

someValues.forEach(x => { let a = 2 + x; console.log(a); });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPositiveGuyView Question on Stackoverflow
Solution 1 - JavascriptLong NguyenView Answer on Stackoverflow
Solution 2 - JavascriptmonnefView Answer on Stackoverflow