Hoisting is a JavaScript mechanism that lets you access variables and functions before you initialize them.

Hoisting such a declaration effectively moves it to the top of its scope.

The JIT compiler then hoists all instances of variable declarations to the top of their scope upon compilation.

JavaScript only hoists declarations of variables, not their initializations.

var

Accessing an uninitialized variable declared with thevarkeyword will returnundefined.

For example:

The above code logsundefinedbecause it callsconsole.logbefore it initializes the variable.

Javascript will only hoist a variable to the top of the scope you declared it in.

Attempting to log the value of a variable outside its declared scope will result in aReferenceError.

let and const

According to theMDNdocumentation onletandconsthoisting,JavaScript also hoists variables declared with theletandconstkeywords.

However, unlike variables declared with thevarkeyword, they are not initialized with anundefinedvalue.

Hoisting Functions

JavaScript hoists functions similarly to variables.

As with variables, it depends on how you declare them.

For example, JavaScript hoists function declarations differently from function expressions.

For example:

JavaScript hoists function declarations but not function expressions.

However, trying to callbarresults in aTypeError.

Here are some ways it’s possible for you to manage hoisting.

Declare Variables Inside Functions

Declare variables inside the functions that will access them.

So ensure that you only declare variables globally if you really need to.

This practice is beneficial when declaring local variables inside a function.

Doing so will ensure the JavaScript compiler does not have to hoist those variables to access them.

Strict mode does not stop hoisting altogether.

Instead, it prevents the most confusing and error-prone forms of hoisting.