Skip to main content
Stack Overflow
  1. About
  2. For Teams

Return to Revisions

13 of 16
Fixed typo
Ran Turner
  • 18.7k
  • 9
  • 60
  • 60

This explanation is taken from an article I wrote at Medium:

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope by the parser which reads the source code into an intermediate representation before the actual code execution starts by the JavaScript interpreter. So, it actually doesn’t matter where variables or functions are declared, they will be moved to the top of their scope regardless of whether their scope is global or local. This means that

console.log (hi); 
var hi = "say hi";

is actually interpreted to

var hi = undefined;
console.log (hi);
hi = "say hi";

So, as we saw just now, var variables are being hoisted to the top of their scope and are being initialized with the value of undefined which means that we can actually assign their value before actually declaring them in the code like so:

hi = "say hi"
console.log (hi); // say hi
var hi;

Regarding function declarations, we can invoke them before actually declaring them like so:

sayHi(); // Hi
function sayHi() {
 console.log('Hi');
};

Function expressions, on the other hand, are not hoisted, so we’ll get the following error:

sayHi(); //Output: "TypeError: sayHi is not a function
var sayHi = function() {
 console.log('Hi');
}; 

ES6 introduced JavaScript developers the let and const keywords. While let and const are block-scoped and not function scoped as var it shouldn’t make a difference while discussing their hoisting behavior. We’ll start from the end, JavaScript hoists let and const.

console.log(hi); // Output: Cannot access 'hi' before initialization 
let hi = 'Hi';

As we can see above, let doesn’t allow us to use undeclared variables, hence the interpreter explicitly output a reference error indicating that the hi variable cannot be accessed before initialization. The same error will occur if we change the above let to const

console.log(hi); // Output: Cannot access 'hi' before initialization
const hi = 'Hi';

So, bottom line, the JavaScript parser searches for variable declarations and functions and hoists them to the top of their scope before code execution and assign values to them in the memory so in case the interpreter will encounter them while executing the code he will recognize them and will be able to execute the code with their assigned values. Variables declared with let or const remain uninitialized at the beginning of execution while that variables declared with var are being initialized with a value of undefined.

I added this visual illustration to help understanding of how are the hoisted variables and function are being saved in the memory enter image description here

Ran Turner
  • 18.7k
  • 9
  • 60
  • 60

AltStyle によって変換されたページ (->オリジナル) /