JavaScript Hoisting with Example
When you execute the javascript code at that time javaScript engine create the global execution context. global execution context means js code starts the execution when the file first load in the browser. the code is not inside any function or any object block that code is in a global execution context. this global execution has two-parts creation and \execution. during the creation part, All the javascript deceleration moved to the top of the code. i.e all javaScript engine by default move these global declared variables and function on the top of your code. this javascript behaviour called "Hosting".
There are two types of hoisting possible in javaScript 1. Variable hoisting 2. Function hoisting
1. Variable Hoisting
in the variable hoisting All the global variable decelerations are moved to the top of the code.
For Example :
console.log("My Fav fruit " + fruit);
var fruit = "Mango";
In the above example, I have declared the fruit variable. when you run this program the javascript engine not throw any error because javascript by default moves this variable to the top when it is executing. technically code looks like following in the execution phase.
var fruit;
console.log("My Fav fruit " + fruit);
fruit = "Mango";
In the execution phase variable is moved top and set the undefined value to this fruit variable. so the output of this code is My Fav fruit undefined.
Comments
Post a Comment