tl;dr

This is tldr for the second half of Javascript Is Sexy’s article titled “JavaScript Variable Scope and Hoisting Explained” only covering variable scope.

Variable Hoisting

  • Variable declaration
    • Inside a function
      • Hoisted (lifted and declared) to the top of the function
// How it's written
function showName() {
  console.log ("First Name: " + name);
  var name = "Ford";
  console.log ("Last Name: " + name);
}

showName();
// How it's actually processed
function showName () {
	var name;
  console.log ("First Name: " + name); // First Name: undefined

  name = "Ford";

  console.log ("Last Name: " + name); // Last Name: Ford
}
  • Outside a function
    • Global context
  • Function declaration
    • Has precedence over variable declaration
    • But not variable assignment
  • Function expressions are not hoisted
var myName = function () {
  console.log ("Rich");
}