0

(function(){
    console.log(1);
    setTimeout (function(){console.log(2);},1000);
    setTimeout (function(){console.log(3);},0);
    console.log(4);
})();

Output:

1
4
undefined
3
2

Why is there an undefined in the output?

ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
Saket Nalegaonkar
  • 160
  • 1
  • 1
  • 14

4 Answers4

5

If you're doing it in the console of the browser itself, then whenever you console.log it prints undefined, see this thread:

Chrome/Firefox console.log always appends a line saying undefined

And there's countless other threads explaining why that happens.

If this isn't in the console but in your JS file itself then there's something else somewhere else in your code that's doing it

Community
  • 1
  • 1
Jayce444
  • 8,725
  • 3
  • 27
  • 43
4

undefined is the return value of your function. It print undefined if you do this in browser console because it's automatically print the result of your function.

Bigdragon
  • 352
  • 1
  • 4
  • 16
2

This is because return value of the function is undefined. So it first log 1,4,return value of function then it will log the values from setTimeout

For example

(function(){
    console.log(1);
    setTimeout (function(){console.log(2);},1000);
    setTimeout (function(){console.log(3);},0);
    console.log(4);
    return 'xyz'

})();

Output will be

1,4,'xyz',3,2
brk
  • 48,835
  • 10
  • 56
  • 78
1

The undefined is the function return,you can try below code:

(function(){
        console.log(1);
        setTimeout (function(){console.log(2);},1000);
        setTimeout (function(){console.log(3);},0);
        console.log(4);
        return 5;
    })();
Kerwin
  • 1,212
  • 1
  • 7
  • 14