javascriptundefinedredefine

Javascript Undefined variable redefined inside function


could you please help me understand why JS works this way here?

var timer = 3;
var func = function() {
  alert(timer);
  var timer = 5;
}
func();

It returns me "undefined".

If I do

var timer = 3;
var func = function() {
  alert(timer);
  timer = 5;
}
func();

it works as expected (alerts 3).

It is something with scopes that I didn't understand correctly. Shouldn't JS overwrite the definition of "timer" after the alert?

Tested just on chrome.

Thank you guys.


Solution

  • var timer = 3;
    var func = function() {
      alert(timer);
      var timer = 5;
    }
    

    This code becomes this when js interprets ;

    var timer = 3;
    var func = function() {
      var timer; // Here local variable timer is undefined
      alert(timer); // here local var timer alerts rather than global var timer 
      timer = 5; // here timer got initialized
    }
    

    This happens because of hoisting concept in javascript. You can read hoisting frome here