DEV Community

Cover image for Understanding Hoisting in JavaScript
Neeraj Kumar
Neeraj Kumar

Posted on

Understanding Hoisting in JavaScript

Hoisting is a concept in JavaScript, not a feature. In other scripting or server side languages, variables or functions must be declared before using it.

In JavaScript, variable and function names can be used before declaring it. The JavaScript compiler moves all the declarations of variables and functions at the top so that there will not be any error. This is called hoisting.

x = "Neeraj Kumar";

alert('x = ' + x); // display x = "Neeraj Kumar"

var x;
Enter fullscreen mode Exit fullscreen mode

functions to the top of their scope by compiler itself just before the execution of code is known as Hoisting.

Also, a variable can be assigned to another variable as shown below.

x = "Neeraj";
y = "Kumar";

alert('x = ' + x);
alert('y = ' + y);

var x;
var y;
Enter fullscreen mode Exit fullscreen mode

Hoisting is only possible with declaration but not the initialization. JavaScript will not move variables that are declared and initialized in a single line.
Example: Hoisting not applicable for initialized variables

alert('x = ' + x); // display x = undefined

var x = "Neeraj";
Enter fullscreen mode Exit fullscreen mode

As you can see in the above example, value of x will be undefined because var x = "Neeraj" is not hoisted.
Hoisting of Function
JavaScript compiler moves the function definition at the top in the same way as variable declaration.
Example: Function Hoisting

alert(Sum(50, 50)); // 100

function Sum(val1, val2)
{
    return val1 + val2;
}
Enter fullscreen mode Exit fullscreen mode

Please note that JavaScript compiler does not move function expression.

Example: Hoisting on function expression

Add(50, 50); // error

var Add = function Sum(val1, val2)
{
    return val1 + val2;
}
Enter fullscreen mode Exit fullscreen mode

Hoisting Functions Before Variables
JavaScript compiler moves a function's definition before variable declaration. The following example proves it.
Example: Function Hoisting Before Variables
alert(UseMe);

var UseMe;

function UseMe()
{            
    alert("UseMe function called");
}
Enter fullscreen mode Exit fullscreen mode

As per above example, it will display UseMe function definition. So the function moves before variables.
Points to Remember :
1.JavaScript compiler moves variables and function declaration
to the top and this is called hoisting.
2.Only variable declarations move to the top, not the
initialization.
3.Functions definition moves first before variables.

Top comments (0)