What is hoisting in JavaScript?As we all know, the variable declaration is one of the basic and essential aspects of any programming language such as C language, C++, etc. However, JavaScript has a small odd, known as Hoisting, which can turn a flawless-looking declaration into a subtle bug. HoistingIn JavaScript, Hoisting is a kind of default behavior in which all the declarations either variable declaration or function declaration are moved at the top of the scope just before executing the program's code. However, it can be considered an advantage because all functions and variable declarations are placed to the top of their scope no matter where they are all declared anywhere in the whole program, even regardless of whether they are declared global or local. Due to the concept of hoisting in JavaScript, we can call a function even before we define the function definition in our program's code. In simple words, we can say that we can use the variables and functions in JavaScript before declaring them because as we discussed above JavaScript compiler moves the declarations of all the variables and functions at the top of their scope so that there will not be an error of any kind. The concept of JavaScript of moving all declarations of the variables and functions to the top of their scope by compiler itself just before the execution of code is known as Hoisting. Note: The important thing to remember is that in JavaScript, function declaration and variable declaration are only hoisted, not initialization.Let us understand what precisely this is: This is the following sequence mostly in which variable declaration and initialization occur. 1. Declaration -> 2.Initialisation/Assignment ->3. Usage Example But as we all aware that JavaScript allows us to declare and initialize the variables simultaneously. This is one of the most common patterns used: Output Note:Another essential thing to remember is that in the backend, JavaScript first declares the variables, functions, and after that initialize them. However, undeclared variables do not exist in the JavaScript until the code assigning them gets executed. So when assigning values to any of the undeclared variables, they are converted as global variables when the assigned code is executed. Therefore we can say that all undeclared variables are global variables.Example |