0

Running the following script in javascript or nodejs or any other javascript environment prints:

undefined
0
1
2
3
4

Script:

for(var i=0;i<5;i++){
    var a = function (i) {
        setTimeout(function () {
            console.log(i);
        },i*1000);
    };
    a(i);
}

Where does the undefined comes from?

Surender Thakran
  • 3,958
  • 11
  • 47
  • 81

2 Answers2

2

When using a REPL environment, the expression you enter is evaluated and its result is returned.

In this case, the result is undefined. It's a side effect of the REPL, it's not part of the output of your code.

user229044
  • 232,980
  • 40
  • 330
  • 338
  • any idea how to remove it from even inside an REPL? – Surender Thakran Apr 11 '15 at 02:10
  • 1
    @SurenderThakran You can't, and there is no reason to want to – user229044 Apr 11 '15 at 02:11
  • it is actually an interview question someone asked me, so was wondering. I tried: for(var i=0;i<5;i++){ var a = function (i) { setTimeout(function () { console.log(i); },i*1000); }; var b = a(i);} which didn't worked. I also tried: for(var i=0;i<5;i++){ var a = function (i) { setTimeout(function () { console.log(i); },i*1000); return null; }; a(i);} which just replaced undefined with null – Surender Thakran Apr 11 '15 at 02:14
2

If you’re running it from the REPL, undefined is the completion value of the expression, which is a(4). a doesn’t return anything, so its return value is undefined, and the REPL prints that. It is not passed to console.log and won’t appear if you run it as a standalone script.

Ry-
  • 218,210
  • 55
  • 464
  • 476