Article -5 min read
🪢 Please Hoist with care in JavaScript
Hoisting is a tool in your JavaScript arsenal, but it should be considered carefully.
JavaScript
Programming
less than a month ago
What is Hoisting in JavaScript?
Hoisting is a behavior in JavaScript where variable and function declarations are moved to the top of their containing scope during the execution phase, regardless of where they are defined in the code. This means you can use a variable or call a function before it’s actually declared in the code.
Example of Hoisting regular JavaScript variables
// First example:
console.log(name); // undefined
var name = "Kim";
// Second example:
console.log(nameAgain); // Uncaught ReferenceError: name2 is not defined
let nameAgain = "Kim";
Example of Hoisting JavaScript functions
// First example:
callMyName(); // "Kim"
function callMyName() {
console.log("Kim");
};
// Second example:
dontCallMyName(); // Uncaught ReferenceError:
// can't access lexical declaration 'dontCallMyName'
// before initialization
const dontCallMyName = () => {
console.log("Kim");
};
Why the bloody hell does Hoisting exist in JavaScript?
Hoisting was introduced to allow developers to use variables and functions before they are defined in the code, making it more flexible to structure your programs. It was a design decision made in JavaScript to provide some level of convenience when organizing and writing code.
So you’ve shown me what Hoisting is… but when do I use it?
That’s the neat thing, you don’t. Nah I’m just messing with you but in all seriousness, in my still fairly inexperienced opinion - to write clean and maintainable code, it’s best to declare all your variables and functions before using them, regardless of hoisting. This practice helps avoid confusion and reduces the risk of unintended behavior caused by hoisting. By following this guideline, you can write more readable and predictable code.