2

I was doing some reading about es2015, trying out some of the examples on the arrow syntax when I came across this code:

var odds = evens.map(v => v + 1);//I understand
var nums = evens.map((v,i) => v + i);//I don't understand

with evens initialized to [0,2,4,6] I get [1,3,5,7] from odds, which I understand.

However I don't understand the result of the the second expression [0,3,6,9]. Essentially I'm not understanding what values are being assigned to the variable i in the second example. Can anyone shed any light on this?

1
  • Read the documentation for Array#map, in particular the part about what parameters it passes to the callback. Commented Dec 15, 2015 at 4:39

1 Answer 1

6

Array.prototype.map function, will call the function passed to it with three parameters, as seen here

  • current element
  • current element's index and
  • the actual array itself

So, in your case, v is the current element and i is the index of the element in the array.

When evens is initialized with [0, 2, 4, 6], it just adds the element with its corresponding index and returns a new array.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.