Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through array of values with Arrow Function [closed]

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?

like image 935
PositiveGuy Avatar asked Nov 17 '15 17:11

PositiveGuy


People also ask

Do arrow functions have closures?

In JavaScript, arrow functions provide a concise syntax for anonymous function expressions stripped off of their OOP baggage. They are a syntactic sugar on a subset of the function capabilities. Both can be used as closures capturing variables of the outer scope.

When you should not use the arrow function?

An arrow function doesn't have its own this value and the arguments object. Therefore, you should not use it as an event handler, a method of an object literal, a prototype method, or when you have a function that uses the arguments object.

Can arrow functions be invoked?

an arrow function is an expr, but we need surrounding parens b/c of "operator precedence" (sorta), so that the final parens to invoke the arrow-IIFE apply to the entire function and not to just the last token of its body.

Do arrow functions automatically return?

Arrow functions allow you to have an implicit return: values are returned without having to use the return keyword. This should be the correct answer, albeit needing a bit more explanation. Basically when the function body is an expression, not a block, that expression's value is returned implicitly.


2 Answers

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

like image 150
Long Nguyen Avatar answered Oct 13 '22 11:10

Long Nguyen


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); }); 
like image 24
monnef Avatar answered Oct 13 '22 11:10

monnef