6

Forgive me if this might be a bit of a noobie question, but this should work shouldn't it?

var elems = [1,2,3,4,5]

for (var i = 0; i <elems.length; i++) {
    return (function(e){
        console.log(e)
    })(i);
}

Meaning, it should spit out

>>node file.js
1
2
3
4
5

For some reason this isn't doing this. Rather when it is run in terminal, it spits out

>>node file.js
1

What am I missing? Could you please elaborate.

thefourtheye
  • 206,604
  • 43
  • 412
  • 459
ApathyBear
  • 6,991
  • 12
  • 48
  • 84

2 Answers2

7

Because you are returning the value returned by the IIFE immediately, in this statement

return (function(e){
    console.log(e)
})(i);

since the IIFE just prints 0 and doesn't return anything explicitly, JavaScript will return undefined by default and exit immediately. To fix this, just drop the return keyword,

(function(e){
    console.log(e)
})(i);

PS: Have you ever wondered, why the return statement in the above code works? To think about it, it is not inside a function. Then technically its an error, right? ;-) I explained this in detail, in this question.

Community
  • 1
  • 1
thefourtheye
  • 206,604
  • 43
  • 412
  • 459
2

When you call the return, it will immediately break out of the loop. If you want to return all the values, you will have to put them in a container and return the container.

Jacob Malachowski
  • 590
  • 1
  • 5
  • 18