Why is the output of the following snippet undefined, 5?
var a=5;
(function(){
    console.log(a);
  var a= b = 10;
  
})();
console.log(a);Why is the output of the following snippet undefined, 5?
var a=5;
(function(){
    console.log(a);
  var a= b = 10;
  
})();
console.log(a); 
    
     
    
    There is something called hoisting in javascript. Hoisting means that all the variables which are declared inside a scope a brought to the top of the scope and declared there and then assigned on their corresponding line.
The above code is same as
var a=5;
(function(){
    var a;
    console.log(a);
    a= b = 10;
  
})();
console.log(a);
In the above function when var a; is declared but not initialized so it will get assignment to undefined automatically. Hence you see undefined in the first log.
And in the second log you see 5 because the previous variable a is inside that function and not available outside. In the outside log the a in global scope will be logged.
