0

I am trying to use forEach method on my array but I am getting undefined instead of a correct result. Could anyone help me and tell me what is wrong with my code?

[0,1,2,3].forEach((x,i) => (x*i)%3);

4 Answers 4

3

The return value of forEach() is undefined, use Array.prototype.map() instead:

var r = [0,1,2,3].map((x,i) => (x*i)%3);
console.log(r);

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

Comments

1

You're using forEach, which doesn't return anything, so the result of calling it is undefined. (forEach also completely ignores the return value of the callback it calls.)

If you want a return value, you probably want map (or possibly reduce), not forEach. For example:

console.log([0,1,2,3].map((x,i) => (x*i)%3));

Comments

1

You're returning nothing inside the forEach, write a console.log for that

Comments

1

This is from https://developer.mozilla.org/

forEach() executes the callback function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable. The typical use case is to execute side effects at the end of a chain.

If you are trying to transform the array, use map() instead

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.