Explore Function Hoisting In Java Script
Posted By : Avilash Choudhary | 30-May-2018
Explore function hoisting in
* Variable hoisting
* Function hoisting
In this article, we are going to explain function hoisting, as it is very tricky. We can create
function name(param1, param2) {
// statements......
}
Function declaration hoists the function definition, these types of functions can be used before they are declared.
test(); // output - Testing.....
function test() {
console.log('Testing.....');
}
NOTE: Never use function declarations inside if/else block In Function expression, we can use the function keyword
const myFunction = function [functionName] (param1, param2) {
// statements....
}
NOTE:
test(); // TypeError: test is not a function
function test() {
console.log('Testing.....');
}
Below are some tricky questions to understand function hoistings.
var test = 1;
function testing() {
test = 10;
return;
function test() {}
}
testing();
console.log(test);
In above example, if we do not pay much attention then we might think the output will be 10. but it has some complexity.
var test = 1;
function testing() {
// hoisted
function test() {}
test = 10;
return;
}
testing();
console.log(test);
Hoisted statement create local test variable and when we are assigning 10 to test, we are assigning to local test variable. when we console the test, it will print 1, because it is pointing to global test variable. Another example,
function testing(){
function test() {
return 3;
}
return test();
function test() {
return 8;
}
}
alert(testing());
The above example will alert 8 because
function testing(){
//Hoisted before
function test() {
return 3;
}
// Hoisted after
function test() {
return 8;
}
return bar();
}
alert(testing());
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
Avilash Choudhary
Avilash has excellent experience in developing mobile and web applications using jQuery , Javascript and PhoneGap. His hobbies are watching and playing cricket.