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

RMAG news

1. 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

2. var ❌ let and const ✅

Use let and const instead of var to declare or initialize variables. Unlike var, variables created with let and const are not hoisted.

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:

// returns undefined since only the declaration is hoisted
console.log(a);

// hoisted
var a = 19;

// ReferenceError: Cannot access ‘b’ before initialization
console.log(b);

// did not get hoisted
const b = 12;

3. “use strict” mode

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.

4. 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 a function expression!);
}
}

setData();

Conclusion

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: gmail

Connect with me on Twitter, LinkedIn and GitHub

Thank you for Reading 🙂

Leave a Reply

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