Useful JS Tips

#11 - Hoisting

2016-01-11 by @squizzleflip

Understanding hoisting will help you organize your function scope. Just remember, variable declarations and function definitions are hoisted to the top. Variable definitions are not, even if you declare and define a variable on the same line. Also, a variable declaration lets the system know that the variable exists while definition assigns it a value.

function doTheThing() {
  // ReferenceError: notDeclared is not defined

  // Outputs: undefined
  var definedLater;

  definedLater = 'I am defined!'
  // Outputs: 'I am defined!'

  // Outputs: undefined
  var definedSimulateneously = 'I am defined!'
  // Outputs: 'I am defined!'

  // Outputs: 'I did it!'

  function doSomethingElse(){
    console.log('I did it!');

  // TypeError: undefined is not a function

  var functionVar = function(){
    console.log('I did it!');

To make things easier to read, declare all of your variables at the top of your function scope so it is clear which scope the variables are coming from. Define your variables before you need to use them. Define your functions at the bottom of your scope to keep them out of your way.