(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?
(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?
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
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.
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
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;
})();