Tutorials References Menu

JS Tutorial

JS HOME JS Introduction JS Where To JS Output JS Statements JS Syntax JS Comments JS Variables JS Let JS Const JS Operators JS Arithmetic JS Assignment JS Data Types JS Functions JS Objects JS Events JS Strings JS String Methods JS String Search JS Numbers JS Number Methods JS Arrays JS Array Methods JS Array Sort JS Array Iteration JS Array Const JS Dates JS Date Formats JS Date Get Methods JS Date Set Methods JS Math JS Random JS Booleans JS Comparisons JS Conditions JS Switch JS Loop For JS Loop For In JS Loop For Of JS Loop While JS Break JS Typeof JS Type Conversion JS Bitwise JS RegExp JS Errors JS Scope JS Hoisting JS Strict Mode JS this Keyword JS Arrow Function JS Classes JS JSON JS Debugging JS Style Guide JS Best Practices JS Mistakes JS Performance JS Reserved Words

JS Objects

Object Definitions Object Properties Object Methods Object Display Object Accessors Object Constructors Object Prototypes Object Reference Object Map() Object Set()

JS Functions

Function Definitions Function Parameters Function Invocation Function Call Function Apply Function Closures

JS Classes

Class Intro Class Inheritance Class Static

JS Async

JS Callbacks JS Asynchronous JS Promises JS Async/Await

JS Versions

JS Versions JS 2009 (ES5) JS 2015 (ES6) JS 2016 JS 2017 JS 2018 JS IE / Edge JS History

JS HTML DOM

DOM Intro DOM Methods DOM Document DOM Elements DOM HTML DOM Forms DOM CSS DOM Animations DOM Events DOM Event Listener DOM Navigation DOM Nodes DOM Collections DOM Node Lists

JS Browser BOM

JS Window JS Screen JS Location JS History JS Navigator JS Popup Alert JS Timing JS Cookies

JS Web APIs

Web API Intro Web Forms API Web History API Web Storage API Web Worker API Web Fetch API Web Geolocation API

JS AJAX

AJAX Intro AJAX XMLHttp AJAX Request AJAX Response AJAX XML File AJAX PHP AJAX ASP AJAX Database AJAX Applications AJAX Examples

JS JSON

JSON Intro JSON Syntax JSON vs XML JSON Data Types JSON Parse JSON Stringify JSON Objects JSON Arrays JSON Server JSON PHP JSON HTML JSON JSONP

JS vs jQuery

jQuery Selectors jQuery HTML jQuery CSS jQuery DOM

JS Examples

JS Examples JS HTML DOM JS HTML Input JS HTML Objects JS HTML Events JS Browser JS Editor

JS References

JavaScript Objects HTML DOM Objects


JavaScript Hoisting


Hoisting is JavaScript's default behavior of moving declarations to the top.


JavaScript Declarations are Hoisted

In JavaScript, a variable can be declared after it has been used.

In other words; a variable can be used before it has been declared.

Example 1 gives the same result as Example 2:

Example 1

x = 5; // Assign 5 to x

elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x;                     // Display x in the element

var x; // Declare x
Try it Yourself »

Example 2

var x; // Declare x
x = 5; // Assign 5 to x

elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x;                     // Display x in the element
Try it Yourself »

To understand this, you have to understand the term "hoisting".

Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).


The let and const Keywords

Variables defined with let and const are hoisted to the top of the block, but not initialized.

Meaning: The block of code is aware of the variable, but it cannot be used until it has been declared.

Using a let variable before it is declared will result in a ReferenceError.

The variable is in a "temporal dead zone" from the start of the block until it is declared:

Example

This will result in a ReferenceError:
carName = "Volvo";
let carName;
Try it Yourself »

Using a const variable before it is declared, is a syntax errror, so the code will simply not run.

Example

This code will not run.

carName = "Volvo";
const carName;
Try it Yourself »

Read more about let and const in JS Let / Const.



JavaScript Initializations are Not Hoisted

JavaScript only hoists declarations, not initializations.

Example 1 does not give the same result as Example 2:

Example 1

var x = 5; // Initialize x
var y = 7; // Initialize y

elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x + " " + y;           // Display x and y
Try it Yourself »

Example 2

var x = 5; // Initialize x

elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x + " " + y;           // Display x and y

var y = 7; // Initialize y
Try it Yourself »

Does it make sense that y is undefined in the last example?

This is because only the declaration (var y), not the initialization (=7) is hoisted to the top.

Because of hoisting, y has been declared before it is used, but because initializations are not hoisted, the value of y is undefined.

Example 2 is the same as writing:

Example

var x = 5; // Initialize x
var y;     // Declare y

elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x + " " + y;           // Display x and y

y = 7;    // Assign 7 to y
Try it Yourself »

Declare Your Variables At the Top !

Hoisting is (to many developers) an unknown or overlooked behavior of JavaScript.

If a developer doesn't understand hoisting, programs may contain bugs (errors).

To avoid bugs, always declare all variables at the beginning of every scope.

Since this is how JavaScript interprets the code, it is always a good rule.

JavaScript in strict mode does not allow variables to be used if they are not declared.
Study "use strict" in the next chapter.