DEV Community

Selen Gora
Selen Gora

Posted on • Originally published at Medium

Javascript hoisting note to myself

A variable can be used before it has been declared.*

x = 24; // Assign 24 to x
console.log(x); // 24
var x; // Declare x
Enter fullscreen mode Exit fullscreen mode

var, let, const Differences

var declaration phase and initialization phase are same level. var variables are hoisted.

let declaration phase after uninitialized state after comes initialization phase.

Hoisting is not valid for a let variable (including for const and class).
Before initialization, the variable is in temporal dead zone and is not accessible. *

Little bit deeper on let, const variables, actually they are hoisting but…

It will throw an exception if you access the variable before the initialisation even if the accessing code is below the declaration (e.g. in a hoisted function declaration that is called too early).

user Bergi has the explanation on stackoverflow

@thefourtheye is correct in saying that these variables cannot be accessed before they are declared. However, it's a bit more complicated than that.

Are variables declared with let or const not hoisted? What is really going on here?

All declarations (var, let, const, function, function*…

Function hoisting?

Function declarations are hoisted

helloFunction(); // Hello hoisting
// function declaration
function helloFunction() {
    console.log('Hello hoisting');
}
Enter fullscreen mode Exit fullscreen mode

Assignment functions(Function expressions) are not hoisted

myNewFunction(); //Uncaught TypeError: myNewFunction is not a function
// function expression
let myNewFunction = function(){
    console.log('Hello hoisting expression');
}
Enter fullscreen mode Exit fullscreen mode

References:
w3schools
YDKJS
@freecodecamp
@freecodecamp

Top comments (0)