Tag Archives: function statement

Hoisting in JavaScript

Everyone’s heard the all too familiar, JavaScript is an interpreted language spiel. That’s only partly true. Certain instances  can catch unwary developers out about this idiosyncratic run-time behaviour.

When a JavaScript engine parses a code file, a global execution environment called the execution context is created. This occurs before the file is executed where functions, variables etcetera are ‘hoisted’ into memory. Think of this as instantiation in other languages.

Hoisting is what allows function calls, which occur before the function definition, to run without throwing an error – as the entire function will be hoisted to memory.

This causes issues where function expressions are used. Function expressions are anonymous functions which are assigned to a variable as opposed to a function statement:

// Function Statement
function doSomething(){
   console.log("something done");
}

// Calling 
functionHolder();

// Function Expression
var functionHolder = function() {
   console.log("doing something else");
}

In this case the variable functionHolder will be hoisted into memory, however it will be ‘undefined’ until the interpreter reaches the actual line where the anonymous function is assigned. At this instance a function object is created and assigned to the variable functionHolder.

For more details about functions expressions, see:
the official description on MDN
JavaScript functions
JavaScript callback functions