You must have heard the word 'Hoisting' or 'Hoisting in JavaScript', especially beginners. So, do you know what it is?
Hoisting in JavaScript is a key concept and can often be confusing for beginners. In this blog, We'll discuss hoisting including what it is, how it functions, and why it's essential.
What is Hoisting?
If you code in JavaScript or learn JavaScript, you might have seen codes in which variables or functions are used before they have been declared in the code. This is done through Hoisting.
Hoisting is the process through which you can use a variable or function before it's been declared in your code by moving the variable and function declarations to the top of their respective scopes.
How does Hoisting works?
Let's understand with an example:
var a = 10;
function printAtConsole(){
console.log("This is the console message");
}
printAtConsole();
console.log(a);
Try running this code.
It works fine right, so what's the catch?
Let's just make a small change and put the function invocation and the console log at the top.
printAtConsole();
console.log(a);
var a = 10;
function printAtConsole(){
console.log("This is the console message");
}
Now, what do you expect the result to be? Let's see:
Generally, you would expect that it would throw an error and most programming languages would also throw an error but here in JS, the code works perfectly fine without any errors. This is the magic of Hoisting.
Also, if you notice here, the function is working fine as usual but the value of 'a' shows 'undefined'. Why?
Let's try this:
printAtConsole();
console.log(a);
function printAtConsole(){
console.log("This is the console message");
}
Now, it shows an error ๐ฐ "Uncaught ReferenceError: a is not defined"
Earlier it was 'undefined' and now it throws an error saying 'not defined'? What is going on?
Let's see the difference b/w 'undefined' and 'not defined'.
undefined v/s not defined
"undefined" is a particular data type in JavaScript that denotes the absence of a value or an uninitialized variable. When a variable is declared but not initialized with a value, the default value is "undefined". For instance, if you declare the variable "x" but don't provide it with a value, "x" will be set to "undefined".
Moreover, "not defined" denotes that the value was not found by the JS engine and is not included in the JS file.
JavaScript Code Execution: Recap
If you read the last blog on the Working of JS and the Execution context, you might remember that when a JavaScript code is executed, a global execution context is created and it has two components: The Memory Component and The Code component.
If you don't know about this concept, you might consider reading the previous blog I published for a better understanding. Click here!
You might have got your answer but let's see the explanation:
The code execution happens in two phases:
The JS engine skims the whole code and allocates memory to all the variables and functions in the code. The variables are assigned the value 'undefined' and in the case of functions, a reference to the function is provided in the memory.
Then in the 2nd phase, the defined values of the variables are taken from the code component and assigned to the variables having values as 'undefined'.
Hoisting in the variables declared with 'var'
Let's see this example again:
printAtConsole();
console.log(a);
var a = 10;
function printAtConsole(){
console.log("This is the console message");
}
When we try to print 'a' in the console which is not yet defined, it works fine without any errors and gives the value as 'undefined' because when the code is executed:
In the 1st phase, i.e., the memory creation phase, 'undefined' is allocated to 'a'.
In the 2nd phase, the console.log() command gets executed before even reaching the initialized value of 'a'.
So, it prints the previously assigned value of 'a' i.e., undefined.
In this way, Hoisting works with the variables declared with 'var'.
Hoisting in functions
In the case of a function, as we can see in the result of the above code, it works fine. How?
As we discussed earlier, in the case of a function, the reference to the whole function is copied in the memory component instead of 'undefined'. Hence, the function can be used even if it is used even before being declared.
Let's verify the function reference thing. Try this code:
console.log(printAtConsole);
console.log(a);
var a = 10;
function printAtConsole(){
console.log("This is the console message");
}
Here is the result of the above code:
You can see here, the whole function is printed in the console which verifies that reference to the function is copied in the memory.
This is how Hoisting in functions work.
Hoisting in the variables declared with 'let' and 'const'
Hoisting in the case of 'let' and 'const' have some more concepts like "The Temporal Dead Zone" due to some strictness of let and const.
I will try to discuss this topic in the next blog. Stay tuned!
Best practice tip ๐
To avoid hoisting errors and bugs, it's always a good idea to declare your variables at the beginning of your code or function. This way, you can be sure that they will be available when you need them.
Conclusion ๐
In conclusion, Hoisting is a fundamental concept in JavaScript that can help you write more efficient and effective code. By understanding how hoisting works and following best practices, you can avoid common errors and bugs and become a more skilled programmer.
Thank you for reading ๐
Any suggestions and corrections are welcome and If you liked this article and learnt something from this, do consider following me on Hashnode and Dev.to for my latest publications. You can also follow me and reach also out to me on Twitter.
Reference:
Namaste JavaScript: Hoisting in JavaScript(var and functions)