javascriptscopeclosureshoisting

Why is a closure able to capture a variable declared after the closure’s definition?


function sayAlice() {
  var sayAlert = function() { console.log(alice); };
  var alice = 'Hello Alice';
  return sayAlert;
}

sayAlice()();

In console, it shows Hello Alice

Question:

var alice(variable declaration) is after var sayAlert, why it still shows the right result, not something like 'undefined'?


Solution

  • Because at the time that sayAlert is actually executed (in the sayAlice()() call), Hello Alice has been assigned to alice. Because of closures in JavaScript, alice is available to sayAlert at execution time.