Hoisting - jellyfish-tom/TIL GitHub Wiki

[SOURCES]

JavaScript has two phases:

  • a parsing phase - where all of the code is read by the JavaScript engine, followed by an
    • memory allocation for variables
    • scope creation
  • execution phase - in which the code that has been parsed is executed
    • code that has been parsed is executed

The term hoisting describes what happens when the JavaScript engine encounters an identifier, such as a variable or function declaration; when it does this, it acts as if it literally lifts (hoists) that declaration up to the top of the current scope

Only the variable declaration is hoisted to the top of its scope; the variable assignment still occurs at the place where we assigned the value

Declarations done with var are hoisted and undefined value is immediately assigned to them. Declarations done with let/const are hoisted but they remain unassigned. Functions also get hoisted (before variables)

The Temporal Dead Zone When a regular variable created using var is hoisted to the top of its scope, itโ€™s initialized with the value undefined (as stated above), which is what allows us to be able to reference a normal variable before it has a value declared through assignment.

console.log(x); // undefined
var x = 10;

because of hoisting it actully is like this:

var x = undefined;
console.log(x); // undefined
x = 10;

Variables declared with let are hoisted, but crucially, they are not automatically initialised with the value undefined, which means that the following code produces an error:

console.log(x); // Uncaught ReferenceError: x is not defined
let x = 10;

to fix

let x
console.log(x); // undefined  (NO ERROR NO MORE BROTHER!)
x = 10;