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);
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);
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));
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