JS Hoisting
👉 Overview
👀 What ?
JavaScript Hoisting is a behavior of JavaScript interpreter that moves variable and function declarations to the top of their containing scope during the compile phase, before the code has been executed. It is a fundamental concept in JavaScript.
🧐 Why ?
Understanding hoisting is crucial for JavaScript programmers because it helps to avoid common bugs related to the order of code execution. It is especially important when using 'var', 'let', and 'const' declarations, function declarations, and function expressions.
⛏️ How ?
To leverage hoisting, always declare your variables and functions at the top of your scope. This will make your code easier to understand and debug. However, be aware that only the declarations are hoisted, not the initializations. This means that if you try to use a variable before it is declared, you will get 'undefined' instead of a reference error.
⏳ When ?
Hoisting has been a feature of JavaScript since its inception, and it is present in all versions of the language.
⚙️ Technical Explanations
During the creation phase, the JavaScript interpreter moves all variable and function declarations to the top of the current scope. This is what we refer to as 'hoisting'. However, it's important to note that only the declarations are hoisted. If a variable is declared and initialized after using it, the value will be 'undefined' because only the declaration was hoisted to the top, not the initialization. Functions, on the other hand, are hoisted with their body, which makes it possible to call a function before it has been declared in the code. But this is not the case with function expressions, as only the variable declaration is hoisted, not the function or its body.