JavaScript has a feature that allows function and variables to be hoisted – this is useful for many developers. Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.
Variables are not hoisted as they cannot be used before their declaration. As shown by the code below, the variable x
was used before it was declared. At this point, the variable x
does not exist. Therefore, an error is thrown when you try to access the value of a variable that doesn’t exist. The value returned by x
is undefined
, as illustrated by the output:
console.log(x);var x = "Educative is amazing!";console.log(x);
Hoisted functions can be used before their declaration. As you can see, the JavaScript interpreter allows you to use the function before the point at which it was declared in the source code. This is extremely useful as the function can be called before defining it. One can then define the function anywhere in the program code. As can be seen from the code below, the Func_Hoisted()
function is called before it is declared. Function declarations can be hoisted.
Func_Hoisted();function Func_Hoisted() {console.log("This function is hoisted!");}
Function definition hoisting only occurs for function declarations, not function expressions. Function expressions are defined with a function as a variable. The definitions look like var b = function()
. This kind of function declarations through expressions makes the function NOT Hoisted. As can be seen in the example below, function a
is defined as a declaration, but function b
is defined as an expression. So, when we call function b
, it gives an error claiming that function b is not defined
.
// This will worka();// This will throw an errorb();// function declarationfunction a() {console.log("This function is hoisted!");}// function expresssionvar b = function () {console.log("This declaration makes function not hoisted!");}