-1

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.

Edoardo
  • 15
  • 4
  • It is called `variable hoisting`.. just look up for the same. – gurvinder372 Mar 03 '16 at 09:52
  • Hoisting. Whenever you define `var xxx` the `var` definition gets moved to the top of the scope (in this case to the very first line of the function; before `alert()`). – h2ooooooo Mar 03 '16 at 09:53

2 Answers2

4
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

Rajan Singh
  • 611
  • 4
  • 9
0

Variable hoisting is annoying in that javascript 'hoists' (send variable declarations) to the top of the current scope.

It doesn't however send initializations to the top of the current scope.

So:

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

becomes:

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

When it is interpreted.

Hoisting is (to many developers) an unknown or overlooked behavior of JavaScript.

If a developer doesn't understand hoisting, programs may contain bugs (errors).

To avoid bugs, always declare all variables at the beginning of every scope.

Since this is how JavaScript interprets the code, it is always a good rule.

Eujinks
  • 390
  • 1
  • 16