Hoisting is one of the most asked Questions in a JavaScript interview. In this blog, we will find out how Hoisting and Scope's mechanism work in JavaScript.
Without wasting your time, Let's begin with Hoisting's explanation.
Hoisting
In general terms, JavaScript provides an interesting feature called Hoisting. It means that we can use a variable or function even before its declaration.
Hoisting is a mechanism in JavaScript where variables and function declarations are moved to the top of their scope before code execution.
NOTE: If you use a Variable or Function and do not declare them somewhere in the code, then it will give an error.
You can use Hoisting with both Variables and Function as shown below in examples.
- Variable Hoisting
Variable hoisting means that you can use a variable even before it has been declared.
console.log(variableHoisting);
var variableHoisting = 'The variable Has been hoisted.'; //Output: Undefined.
The above prints 'undefined' because only the variable declaration is moved to the top and not its definition.
The above code works in Interpreter like this 👇👇👇
var variableHoisting;
console.log(variableHoisting);
variableHoisting = 'The variable Has been hoisted';
//Output: The variable Has been hoisted
- Function Hoisting
Function hoisting means that you can use function even before function declaration is done.
isFunctionHoisted();
function isFunctionHoisted() {
console.log("Yes!");
}
// Output: Yes
This shows that the JavaScript interpreter allows the user to use the function before its declaration.
Note: You cannot use Function Hoisting when you have used Function Expression. If you use Function Expression and use Function Hoisting, then it will result in an error.
Let's see with an example what the above note exactly means.
funcName(); // ReferenceError: funcName is not defined
funcExpression(); // TypeError: undefined is not a function
var funcExpression = function funcName() {
console.log("Definition is not hoisted!");
};
You can see that function's name doesn't get Hoisted as it is part of Function Expression.
Summary
I hope your doubts revolving around the concept of Hoisting must have cleared. Let's summarize what we have learned in this blog:
- Hoisting is a mechanism in JavaScript where variables and function declarations are moved to the top of their scope before code execution.
- We can use Hoisting with both Variables and Functions.
- JavaScript only Hoists declarations, not Initializations.
- You cannot use Function Hoisting when you have used Function Expression.
This is how Hoisting works in JavaScript. I wish to meet you in my next blog.
Till then keep JavaScripting and Stay Tuned !!