DEV Community

Selen Gora
Selen Gora

Posted on • Originally published at Medium

1 2

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)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay