4 Habits to Avoid Bugs related to Hoisting in your JavaScript Code

4 Habits to Avoid Bugs related to Hoisting in your JavaScript Code

Declaring variables at the beginning of the scope

By declaring variables at the beginning of the scope you ensure that these variables are accessible throughout that scope, avoiding any confusion caused by hoisting.

const data = 12;
const variable = "some data";

// other code

var ❌ let and const ✅

Use let and const instead of var to declare or initialize variables.

Variables declared with var are hoisted to the top of their scope and initialized with undefined. That's why accessing them before the declaration line will result in undefined.

On the other hand, variables created with let and const are also hoisted to their scope, but not initialized. That's why accessing them before the declaration line results in a ReferenceError.

This behavior is called the "Temporal Dead Zone" (TDZ).

Also let and const are only accessible within the block they are declared in. This eliminates the possibility of issues of hoisting by variables declared with var.

Example:

console.log(x); // undefined (hoisted, initialized with undefined)
var x = 10; 

console.log(y); // ReferenceError: Cannot access 'y' before initialization (not initialized)
let y = 5;

console.log(z); // ReferenceError: Cannot access 'z' before initialization (not initialized)
const z = 7;

"use strict"

Enabling strict mode directive at the beginning of your code can prevent some hoisting-related problems.

"use strict";

In strict mode, using an undeclared variable throws an error.

Use arrow functions and expressions inside a block scope

Using arrow functions and expressions in block scope instead of normal functions.

Function declarations are hoisted along with their entire definition meaning you can call a function before its declaration in the code.

Arrow functions and expressions are defined at the point of use, eliminating confusion. Since they are not hoisted they don't create any errors.

Example:

function setData() {
    // Calling the function before declaration throws error
    // Error: Cannot access 'myFunc' before initialization
    myFunc();

    // Using arrow function
    const myFunc = () => {
      console.log("This is an arrow function");
    }
}

setData();

Conclusion

Writing JavaScript code isn't challenging, writing code which is both readable and bug free is challenging.

If you found this blog post helpful, please consider sharing it with others who might benefit. You can also follow me for more upcoming content on JavaScript, React, and other web Development topics.

For paid collaboration, you can mail me at: mail.shubhsharma19@gmail.com

Connect with me on Twitter, LinkedIn, and GitHub.

Thank you for Reading :)

Did you find this article valuable?

Support Shubh Sharma by becoming a sponsor. Any amount is appreciated!