Understanding the basics of Hoisting
Posted By : Kiran Joshi | 31-Oct-2018
Hoisting
In simple terms lifting or raising up something. In javascript, it means the functions and variables are available even before the execution phase starts. To understand it let's understand the necessary insights of Javascript.
Everytime you write a program in javascript, it runs in an environment and that environment is called execution context.
There are two types of execution contexts:
1. Global Execution Context, 2. Execution Context created every time after a function is created.
1. Global Execution Context runs code which is not inside any function and is associated with the global object, for example writing location and location.window is exactly same in a browser, as the window is the global object of the browser.
2. Execution Context associated at block level runs code every time a function is called and creates a new execution context.
Note: Every time a function is called the new execution context is pushed to the top of the global execution context, which makes an execution stack.
The execution contexts are associated with an object. This object has 3 variables attached to it which are called its properties:
i. Variable Object
ii. Scope
iii. this keyword
How an execution context is created?
There are two phases to create an execution context:
a. Creation Phase
b. Execution Phase
a. Creation Phase has three following steps
i. Creation of Variable Object: creates an argument object which contains all the arguments passed into the function.
ii. Creation of scope chain scans the code for declaration:
1. If there are functions created a property will be created in the variable object pointing to the function. Which means you can call a function before its declaration.
calcAge(1965); // output- 53
function calcAge(year){
console.log(2018 - year);
}
calcAge(1965); // output- 53
2. for every variable a property will be created in vo and set to undefined.
console.log(age); // output - undefined
var age = 50;
console.log(age); //output - 50
iii. Determine value of this variable.
Note: All the functions are stored inside Variable object before code execution.
b. Execution Phase: The code of the function that generated the current execution is run line by line.
Thanks.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Kiran Joshi
Kiran is a Frontend developer and have knowledge of HTML5, SASS, Bootstrap, and Javascript. She has working knowledge of ReactJs as well.