JavaScript creation date: update date:

Understanding JavaScript Hoisting

Hoisting is a concept that describes how JavaScript stores variable and function declarations in memory during the compilation phase. For variables declared with var, hoisting moves these declarations to the top of their function scope during compilation. However, while variable declarations are hoisted, their values are not assigned. This means if you access such a variable before its assignment, you’ll get undefined.

When using variables declared with let/const before their declaration, we encounter a ReferenceError. This might lead people to believe that let/const don’t hoist. In fact, let/const do exhibit hoisting behavior, but with two key differences from var:

Function declarations are also hoisted. Unlike variables, function hoisting creates the complete function object, allowing you to call functions before they appear in your code.

It’s important to note that function expressions behave differently. Their hoisting behavior matches the variable type they’re declared with. For example, if a function foo is declared as a variable with var, accessing it before the declaration will yield undefined, and attempting to call undefined results in an error:

Similarly, for a function foo declared with let, accessing it before declaration places it in the temporal dead zone, resulting in a reference error:

Reference

Explain What Hoisting Is in JavaScript | ExplainThis