Hoisting in Javascript

Hoisting is a process of pushing the declared variables to the top of the program while running it. For Ex:

doSomething(foo); // used before
var foo; // declared later

 In this mechanism, a JavaScript VM does two things while running a program:

  1. First scan the program, collect all the variable and function declarations and assign memory spaces for it.
  2. Run the program now by filling variable values assigned any, if not, fill undefined

In the above code snippet, console.log prints “undefined”. It is because in the first pass variable foo is collected. VM looks for any value defined for variable foo. This hoisting can result in many JavaScript code situations where code can throw errors in some places and uses undefined silently in another. You should be knowing hoisting to clear the ambiguity! See a few examples!