Hoisting in JavaScript

Lindsaymecher
The Startup
Published in
3 min readJul 7, 2020

Upon reading the following lines of code, it might be reasonable to assume that lines 3 and 5 would produce errors, given that the functions are invoked before they have been declared.

These functions are invoked before they are declared.

This code actually runs just as intended, because of JavaScript’s default behavior of moving declarations to the top of their scope.

When JavaScript code is run, all the var variable declarations and standard function declarations are hoisted to the top level within their scope by the JavaScript interpreter. That is, if you have functions and variables declared globally, those function declarations are hoisted to the top of the file. If you have variables declared inside of a function, they will be hoisted to the top of that function. The definitions of the variables, however, are NOT hoisted.

Example of hoisting within the scope of this function.

Line 34 will log undefined, because while the declaration of the variable sentence has been hoisted to the top of the function, its definition has not. It’s definition at the time it is logged on line 34 is undefined.

Variables defined with let or const, and functions defined using ES6 syntax are not hoisted. This is an example of a function that cannot be hoisted, given that it is declared using ES6 arrow function syntax.

Functions declared using ES6 syntax are not hoisted.

On line 33, the following error is logged:

(Uncaught ReferenceError: Cannot access ‘hoisting’ before initialization)

Variables declared using let or const are not hoisted

In either case with the weather or language variables, they are not hoisted and are therefore unavailable to be logged before they are initialized. This code will also produce an error like the previous example.

Conclusion

Hoisting is a unique behavior of JavaScript. It is best practice to avoid the use of hoisting in ones code. Using const and let for variable declarations is a good way to avoid any issues with hoisting or scope. I personally prefer writing functions using ES6 arrow function syntax as well. It is a good idea to define all the variables you need at the top lines of their scope. For example, global variables within your file should be declared and defined at the top of the file, and it is a good rule of thumb to use const to declare and define variables, unless you know that variable assignment will change later, in which case you can use let.

--

--

Lindsaymecher
The Startup

Full-stack developer. Aspiring polyglot. Chicagoan.