1

I just would like to understand why this works:

let newArray = [0,1,2,3].map(elem => elem + 1);
console.log(newArray);

and this doesn't:

let newArray = [0,1,2,3].map(elem => elem++);
console.log(newArray);

3

3 Answers 3

4

That is related to the ++ operator.

return elem++ means return the original value of elem, and after that, elem value will be increased.

To fix this, use ++elem.

Refer to ++ operator.

let newArray = [0,1,2,3].map(elem => ++elem);
console.log(newArray);

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

Comments

0

if you want return elem after increase you should use ++ operation like this

let newArray = [0,1,2,3].map(elem => ++elem);
console.log(newArray);

Comments

0

it is because you are returning the values before increment. try this

let newArray = [0,1,2,3].map(elem => ++elem);
console.log(newArray);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.