This is an old revision of the document!
Table of Contents
Java Script Hoisting
Hoisting in JavaScript is a behavior where variable and function declarations are moved, or “hoisted,” to the top of their containing scope during the compilation phase, before the code is executed. It's important to note that only the declarations are hoisted, not the initializations.
Variable hoisting
The variable declaration using var is hoisted, but the initialization is not. So, if you reference a variable before it's initialized, it will return undefined.
Example:
console.log(a); // undefined var a = 5; console.log(a); // 5
What's happening behind the scenes is something like this:
var a; console.log(a); // undefined a = 5; console.log(a); // 5
Functions
Function declarations are also hoisted, and this includes both the name and the code of the function.
Example:
console.log(myFunction()); // "I'm hoisted!" function myFunction() { return "I'm hoisted!"; }
In this case, the entire function declaration is hoisted, so you can call it even before the point in the code where you define it.
Only the variable declaration is hoisted, not the initialization with the function value.
Example:
console.log(myFunc); // undefined console.log(myFunc()); // TypeError: myFunc is not a function var myFunc = function() { return "Hello!"; }; console.log(myFunc()); // "Hello!"
Since myFunc is defined using a function expression with var, the variable declaration is hoisted, but the initialization with the function value is not. So, at the point where we first try to call myFunc(), the variable myFunc is undefined, and attempting to call it as a function results in a TypeError.
Had myFunc been declared with let or const, attempting to access it before its declaration would result in a ReferenceError instead.