bookmark_borderWhat is hoisting in JavaScript?

What is hoisting is one of the standard JavaScript recruitment questions. For some devs it’s one of the quirks of JavaScript, for others it allows understanding the language deeper. Let’s take a look at the example:

console.log(foo);  //returns undefined not ReferenceError exception 
var foo; 

Console.log will not throw the exception. It will print undefined.

Why?

In most of the programming languages, we should have some ‘variable undeclared’ exception. In JavaScript, when the code is executed, the declarations of the variables (declared using var keyword, but not let!) and functions are hoisted, moved to the top (of the scope).

Important thing to notice is that initializations are not hoisted.

console.log(foo);  //returns undefined  
var foo = “bar”; 

But why do we need it?

Well, if we need it or not is a good question, but let’s take a look at the example of how hoisting can be useful. As I said before – declarations of functions are also moved up. Therefore we can use the function before it’s declared:

sayHello("Mark");

function sayHello(name) {
  console.log("Hello " + name);
}

To read more about the hoisting see: https://developer.mozilla.org/en-US/docs/Glossary/Hoisting