Another unusual thing about variables in JavaScript is that you can refer to a variable declared later, without getting an exception. This concept is known as hoisting. Variables in JavaScript are in a sense “hoisted” or lifted to the top of the function or statement. However, variables that are hoisted will return a value of undefined. So even if you declare and initialize after you use or refer to this variable, it will still return undefined.
/** * Example 1 */ console.log(x === undefined); // true var x = 3; /** * Example 2 */ // will return a value of undefined var myvar = "my value"; (function() { console.log(myvar); // undefined var myvar = "local value"; })();
One Important things to remember is Only function declaration gets hoisted to the top and not the function expression.
/* Function declaration */ HoistedFun(); // "I am hoisted" function HoistedFun() { console.log("I am hoisted"); } /* Function expression */ FunctionExp(); // TypeError:FunctionExp is not a function var FunctionExp = function() { console.log("Hoisetd"); };