Skip to content

Instantly share code, notes, and snippets.

@nifl
Created April 3, 2014 18:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nifl/9959496 to your computer and use it in GitHub Desktop.
Save nifl/9959496 to your computer and use it in GitHub Desktop.
JS Hoisting

Hoisting - Concept of program load order

First, memory is set aside for all necessary variables and declared functions.

// How a function is built by humans
function sumOfSquares (a, b) {
  
  var x = add(a*a, b*b);
  return x;
  
  function add(c, d) {
    var a = c + d;
    return a;
    
  }
}

// How javascript loads it
function sumOfSquares (a, b) {
  
  // declared stuff is hoisted to the top of scope
  // before operational code is run
  var x = undefined;
  function add(c, d) {
    var a = c + d;
    return a;
  }
  
  var x = add(a*a, b*b);
  return x;
}

Function expressions are never hoisted. They are treated as assignments.

Avoid hoisting issues

If using function expressions, place variable declarations and assignments at the top and put conditional code at the bottom. That way, variables are assigned immediately after being hoisted.

Or

Use declared functions as those will be hoisted and execution will occur later as conditionals fall to the bottom.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment