/ #ffffff

JS Hoisting

JS Hoisting refers to the process by which function and variable declarations are placed into memory before any code is executed.
This allows you to use a them before you it's declared in your code.

Only the declarations are hoisted, not the initialization.

Variables

1var num; // declaration
2num = 4; // initialization
3
4// declaration and initialization but 
5// only var hello = undefined; will be hoisted
6var hello = 'world';

let and const declarations are not hoisted. A ReferenceError will be thrown if it's tried to be accessed before it's initialized.

var is hoisted to the top of it's scope. This can be either the global scope or function scope.

Functions

1hoisted(); // Output: "This function has been hoisted."
2
3function hoisted() {
4  console.log('This function has been hoisted.');
5};

Function declarations are hoisted.

1expression(); //Output: "TypeError: expression is not a function
2
3var expression = function() {
4  console.log('Will this work?');
5};

Function expressions are not hoisted.

Resources