0

I am trying to understand/comprehend .forEach loop in Javascript.

Now, I get it simply

let numberArray = [1, 2, 3, 4] 

numberArray.forEach(x => {
console.log(x) 
})

As expected it would return output

1
2
3
4

Now, Since forEach is a function, I decided to return something and store its value

 let numberArray = [1, 2, 3, 4] 

let newNum = numberArray.forEach(x => x) 

console.log(newNum)

This is returning undefined when I am clearly returning something and it again it is a function.

Can someone tell me what am I missing here? I mean I the background of forEach loop

[Update:] I know many other ways to achieve my goal, I am more interested to know more about this behaviour for forEach

Alwaysblue
  • 9,948
  • 38
  • 121
  • 210
  • 3
    That the job of `map` not `forEach`: [`Array.prototype.map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map). – ibrahim mahrir Dec 15 '18 at 16:30
  • @soktinpk I know about the map but was just messing around and evaluating result of JS – Alwaysblue Dec 15 '18 at 16:30
  • `.forEach` doesn't use return values, or return anything itself. That's what `.map` is for. – Alnitak Dec 15 '18 at 16:30
  • 2
    `forEach` is a `Function` returning `void 0` (or `undefined`, really). It acts on the `array`, returning **nothing**. You probably wanted `map` instead. If you're familiar with any other **non weak-typed language** it's a `void` function/method, so you're trying to log the result of a `void` function. – briosheje Dec 15 '18 at 16:31
  • Do you want `newNum` to be the sum of the numbers in the array? If so then take a look at: [`Array.prototype.reduce`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce). – ibrahim mahrir Dec 15 '18 at 16:32
  • Possible duplicate of [For-each over an array in JavaScript?](https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript) – Armen Michaeli Dec 15 '18 at 16:33

3 Answers3

5

Array#forEach does not return anything, it makes an operation on every element in a specified array then returns undefined.

You are probably looking for Array#map which as well as Array#forEach makes an operation on every element in some array then returns the result as a new array.

let numberArray = [1, 2, 3, 4];
let newNum = numberArray.map(x => x);

console.log(newNum);

"As expected it would return output" - no, it was not returned. It was logged into console by console.log function.

kind user
  • 40,029
  • 7
  • 67
  • 77
  • Thanks a lot for your answer. If you can answer following as well `forEach` takes a callback and I am returning something in that callback. – Alwaysblue Dec 15 '18 at 16:36
  • 1
    @VarunBindal It's not returning anything. And even if you do, and return something, it won't be included in the result, it will still return `undefined`. `Array#forEach` was meant to iterate over an array and make some external or mutating operation. It will modify existing array. It won't return a new one. You can read more at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach – kind user Dec 15 '18 at 16:39
  • 1
    @VarunBindal the `forEach` argument (the callback) is (like the `forEach` method itself) a `void` function, meaning that its result is **unused** in the `forEach` prototype code. In a nutshell, returning `x` or not returning anything in the foreach callback will equally act on it. That method was meant to iterate by **reference** (if you're not working with an array of primitives like you are) the original array, **altering it** but **without** returning a new one. – briosheje Dec 15 '18 at 16:41
  • @briosheje This is what I was exactly looking for. The understanding of `forEach` rather got lot of answers/comments suggesting alternative. Still glad that people answered and contributed in their own way. – Alwaysblue Dec 15 '18 at 16:43
  • 1
    @VarunBindal then the best you can (always) do for educational purposes is to take the official MDN link (as provied by kind user above), navigate to the "polyfill" section and see the polyfill implementation, here is the direct link to the div: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Polyfill . As you can see, you can find the whole implementation of it, this should help you to properly understand what happens behind `forEach`. To answer to your question, read point 8 ("return undefined") – briosheje Dec 15 '18 at 16:45
1

This case you will get the same array back with the forEach:

let array = [1, 2, 3, 4];

  array.forEach(i => {
    i => i;
  });

  console.log(array);

Note that you will use .forEach() to iterate on collections and .map() to actually create a new array.

EDIT:

To clarify, another example:

let array = [1, 2, 3, 4];
  var myNumber = 1;

  array.forEach(i => {
    myNumber = i;
  });

  console.log(myNumber); // 4

Here, every iteration the variable myNumber value will change to the value of i. On the end of the iterations the value of myNumber will be the value of the last element of the array. Hope it helps!

  • 1
    What is `i => i;` supposed to be? It just declares an anonymous arrow function and discard it immediately, for each item in the array. – ibrahim mahrir Dec 15 '18 at 16:34
  • Agree that it is pretty useless. But OP's question was about that. Nonetheless I already point that use map to create a new array, and use .forEach to only iterate an existing one. – dotnetdev4president Dec 15 '18 at 16:36
  • If you log `array` already you don't even need to put the `foreach` at all. I would suggest you to resee / test your code, since the addition you provided currently does nothing neither to make forEach more understandable, nor to provide a working example. – briosheje Dec 15 '18 at 16:37
  • frankly, I think doing `i => i;` is useless here and not even relevant but thanks for answering though. I am not the one to downvote your answer here :) – Alwaysblue Dec 15 '18 at 16:38
  • I agree with you, it is pretty useless, I updated my post to explain forEach more. – dotnetdev4president Dec 15 '18 at 16:50
  • 1
    Upvoting partially because whoever downvoted this is not really thinking objectively in terms of useful answers. That and I think this actually better explains what `#forEach` does than the accepted answer which focuses on `#map` – Lawrence Johnson Dec 15 '18 at 17:02
  • 1
    @LawrenceJohnson The answer is edited. Previously the answer was sort of vague, The marked answer have a better explanation in the comment. Upvoted this answer as well :) – Alwaysblue Dec 15 '18 at 22:24
0

forEach doesn't return anything. It uses each value in the array as a first argument to call the function you're providing.

raphaelSeguin
  • 449
  • 3
  • 12