-4

I just started to learn javascript and programming overall. I found these examples and trying to figure out results of those two functions.

First:

(function(){
  var x = y = 11; 
})();  
console.log("x = " + (typeof x !== 'undefined')); 
console.log("y = " + (typeof y !== 'undefined'));

Results are true and false. Is it because var x is declared with var keyword so it is local var and y is not?

and second example:

(function(){
  console.log("a");
  setTimeout(function(){console.log("x")}, 1000);      
  setTimeout(function(){console.log("y")}, 0);      
  console.log("b"); 
})(); 

Please explain me the second example? If I got it right, setTimeout will wait for execution even if time is set to 0.

Thanks

wired
  • 438
  • 4
  • 12

1 Answers1

2

First: Correct. If you'd remove the 'var' from the 'x'-declaration that variable would also be available outside the function scope.

Second: The javascript function 'setTimeout' starts an asynchronous operation. In other words, the passed function gets added at the end of the queue to be operated at a later time, even if the passed time is 0ms. The 'console.log' functions run synchronously, so they always will be executed before the functions given with the 'setTimeout'-function.

Richard
  • 390
  • 3
  • 10