JavaScript Hoisting Examples

JavaScript Hoisting with Examples

Hoisting is a JavaScript default behavior that moves the declaration of variables and functions at the top of the current scope during the compilation phase before the code is executed. This means we can use variables and functions before declaring them.

Hoisting is applied only for declaration, not initialization. It is required to initialize the variables and functions before using their values. Hoisting works differently for variables and functions. 

Hoisting occurs because JavaScript separates the compilation phase and the execution phase. During compilation, the JavaScript engine scans through the code and finds the variable and function declarations. It allocates memory for these declarations, regardless of their actual position in the code. This allows you to access these variables and functions before their declarations are written into the code.

However, it’s important to note that only the declarations are hoisted, not the initializations or assignments. In the case of variables, the keyword var is hoisted, and let and const do not allow hoisting.

1. JavaScript Variable Hoisting:

When a variable is hoisted, only the declaration is moved to the top, not the initialization, while the assignment/ initialization remains in its original place. This means that the variable is accessible in its scope before it is declared and as a result, if you try to access a variable before it is assigned a value, it will have the value ‘undefined’. What we discussed above is given in the below example

Example: JavaScript Variable Hoisting- access a variable before it is assigned a value
<html>
<head>
    <title>JavaScript Variable Hoisting- access a variable before it is assigned a value example</title>
</head>
<body>
    <script>
        console.log(x); // Output: undefined
        var x = 10;
    </script>
</body>
</html>

The above code is actually interpreted like this by the JavaScript engine during hoisting:

<html>
<head>
    <title> JavaScript Variable Hoisting- access a variable before it is assigned a value example </title>
</head>
<body>
    <script>
        var x; // Variable declaration is moved to the top
        console.log(x); // Output: undefined
        x = 10; // Variable initialization
    </script>
</body>
</html>
Output:

JavaScript Variable Hoisting- access a variable before it is assigned a value

In the example above, even though the variable x is accessed before its declaration, it doesn’t throw an error. This is because the declaration is hoisted to the top, but the assignment of 10 remains in its original position. So, when console.log(x) is executed, x exists but has the value undefined.

When a variable x is used before it is declared. The program works well and displays the result as 100. What we discussed above is given in the below example

Example: JavaScript Variable Hoisting
<html>
<head>
    <title>JavaScript Variable Hoisting example</title>
</head>
<body>
    <script>
        x = 100;
        document.write(x); //100
        var x; // Variable declaration
    </script>
</body>
</html>

Output: 100

The above code is actually interpreted like this by the JavaScript engine during hoisting:

<html>
<head>
    <title>JavaScript Variable Hoisting example</title>
</head>
<body>
    <script>
        var x; // Variable declaration
        x = 100;
        document.write(x); //100        
    </script>
</body>
</html>

When a variable is used with the let keyword, the variable is not hoisted. The reason because while using let, the variable must be declared first. As a result, if you try to access a variable before it is assigned a value, it will throw a ReferenceError. What we discussed above is given in the below example.

Example: JavaScript Variable Hoisting using let
<html>
<head>
    <title>JavaScript Variable Hoisting using let example</title>
</head>
<body>
    <script>
        x = 10;
        console.log(a);
        let x; // error
    </script>
</body>
</html>
Output:

JavaScript Variable Hoisting using let

The same goes for the const variable also, if a variable is used with the const keyword, that variable is not hoisted rather throws an error saying ‘const’ declarations must be initialized while declaring. The reason because while using const, the variable must be declared first. As a result, if you try to access a variable before it is assigned a value, it will throw a Syntax Error. What we discussed above is given in the below example.

Example: JavaScript Variable Hoisting using const
<html>
<head>
    <title>JavaScript Variable Hoisting using const example</title>
</head>
<body>
    <script>
        x = 10;
        console.log(a);
        const x; // error 'const' declarations must be initialized.
    </script>
</body>
</html>
Output:

JavaScript Variable Hoisting using const

2. JavaScript function Hoisting:

Function declarations are fully hoisted, which means that both the function name(declaration) and its body(implementation) are moved to the top of the scope. This allows you to call the function before its actual declaration in the code. In other words, this allows you to call a function before it appears in the code. What we discussed above is given in the below example.

Example: JavaScript function Hoisting
<html>
<head>
    <title>JavaScript function Hoisting example</title>
</head>
<body>
    <script>
        document.write(addition(10, 20));
        function addition(a, b) {
            return a + b;
        }
    </script>
</body>
</html>

Output: 30

The above code is effectively interpreted like this by the JavaScript engine during hoisting:

<html>
<head>
    <title>JavaScript function Hoisting example</title>
</head>
<body>
    <script>        
        function addition(a, b) {
            return a + b;
        }

        document.write(addition(10, 20));
    </script>
</body>
</html>

In this example, the function addition is called before its declaration, but it works because the function declaration is hoisted to the top. When a function is used as an expression, such as a function assigned to a variable is not hoisted, an error occurs because only function declarations are hoisted. When a function is used as an expression, and assigned to a variable using var keyword, TypeError is thrown. What we discussed above is given in the below example.

Example: JavaScript function Hoisting using function expression with var
<html>
<head>
    <title>JavaScript function Hoisting using function expression with var example</title>
</head>
<body>
    <script>
        // This will work
        fooDeclare();

        // This will throw an error
        fooExpr();

        // function declaration
        function fooDeclare() {
            console.log("This function declaration is hoisted!");
        }

        // function expression
        var fooExpr = function () {
            console.log("This function expression makes function not hoisted!");
        }
    </script>
</body>
</html>
Output:

JavaScript function Hoisting using function expression with var

When a function is used as an expression, and assigned to a variable using the let keyword, ReferenceError is thrown. What we discussed above is given in the below example

Example: JavaScript function Hoisting using function expression with let
<html>
<head>
    <title>JavaScript function Hoisting using function expression with let</title>
</head>
<body>
    <script>
        // This will work
        fooDeclare();

        // This will throw an error
        fooExpr();

        // function declaration
        function fooDeclare() {
            console.log("This function declaration is hoisted!");
        }

        // function expression
        let fooExpr = function () {
            console.log("This function expression makes function not hoisted!");
        }
    </script>
</body>
</html>
Output:

JavaScript function Hoisting using function expression with let

It’s worth noting that hoisting applies to both variable and function declarations using the var keyword. However, hoisting does not occur for variables declared with let or const keywords. They are hoisted to the top of their block scope but are not initialized until their actual declaration. Attempting to access them before the declaration will result in a ReferenceError.

Note: It’s important to note that function expressions, such as functions assigned to a variable, are not hoisted. Only function declarations are hoisted.

To write clean and maintainable code, it’s generally recommended to declare variables and functions before using them, regardless of hoisting. This helps improve code readability and avoid any potential confusion or bugs caused by relying on hoisting. In other words, it is considered a best practice to declare variables and functions at the beginning of their respective scopes to avoid confusion, any unexpected behavior, and potential bugs caused by hoisting.

It’s important to note that hoisting only moves the declarations, not the actual code. Hoisting can be a useful feature, but it can also lead to confusion if not understood properly.

Leave a Reply

Your email address will not be published. Required fields are marked *