Skip to content

Latest commit

 

History

History
75 lines (52 loc) · 1.15 KB

File metadata and controls

75 lines (52 loc) · 1.15 KB

What is variable hoisting?

  • Variable Hoisting means a variable declaration is automatically hoisted to top of its enclosing scope.
  • Anonymous Function must declare before its executing.

Example 1 - Variable Hoisting

"use strict";

console.log(a); //undefined
var a = 1;
  • Above code is same as follow:
"use strict";

var a;          // The variable declaration is automatically hoisting to the top in same scope.
console.log(a); //undefined
a=1;

Example 2 - Function Hoisting

  • A function is also hoisting.
"use strict";

function foo(){
    console.log(a);     //undefined
    var a = 1;
}
foo();
"use strict";

foo();
function foo(){
    console.log(a);     //undefined
    var a = 1;
}

Example 3 - Anonymous Function

  • Anonymous Function must declare before its executing.
  • Both below code are ERROR - foo is not a function.
"use strict";


foo();      // error: foo is not a function.
var foo = function(){
	console.log('hiroko');
};
"use strict";

var foo;        // foo is undefined.
foo();          // you can't execute undefined.
foo = function(){
    console.log('hiroko-2');
};