JavaScript Function Hoisting

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.

This means that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local. Hoisting mechanism only moves the declaration. The assignments are left in place. That is why we are able to call functions before we wrote them in code.

Because the JavaScript engine reads a JavaScript file from top-to-bottom, it would make sense if we had to define a function before we invoked it:

function myFunc () {
return 'Hello, world!';
}

myFunc();
// => "Hello, world!"

However, we can invert those two steps and everything works fine:

myFunc();

function myFunc () {
return 'Hello, world!';
}
// => "Hello, world!"

This looks as though we’re invoking the function prior to declaring it. But JavaScript engine has the two-phase nature . During the compilation phase, the engine skips right over the invocation and stores the declared function in memory:

// The engine ignores all function invocations during the compilation phase.
myFunc();

function myFunc () {
return 'Hello, world!';
}

By the time the JavaScript engine reaches the execution phase, myFunc() has already been created in memory. The engine starts over at the top of the code and begins executing it line-by-line.

The term for this process is hoisting because it feels a bit like your declarations are being hoisted, or raised, to the top of the current scope.

The best way to avoid any confusion brought on by function hoisting is to simply declare your functions at the very top of your code.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store