Ahmet Kapusuz

How does JavaScript hoisting work

Hoisting! One of the most “unique” and maybe as some people called “weird” feature of JavaScript. As a developer who has a Java background I can admit that this was kind of a different feature for me. But after I’ve learned the logic behind it, it has become yet another feature of JavaScript for me. Let’s talk about the logic and rules behind it.

It’s kind of a chicken or the egg problem in the end, as Kyle Simpson explained it beautifully in one of his YDKJS books.

I think one of the key points is to know that JavaScript compiler treats variable declarations and value assignments differently. JavaScript compiler processes all declarations before executing any part of your code. Let’s explain it with some examples.

console.log(foo);
var foo = 2;

When you saw a code like above, it’s normal that you expect to get a reference error on the console, especially if you’re coming from a Java background like me. But JavaScript behavior here is different, JavaScript processes all variable declarations before running other code parts. So it means that, it already know that a variable named foo is declared, but it doesn’t know about the value of foo. So ‘undefined’ will be printed on the screen.

What about functions?

JavaScript function declarations are also hoisted, but function expressions are not.

console.log(bar());

function bar() {
 return 'bar';
};

Above code will print ‘bar’ on console. As you can see, function declaration is also processed before function call.

console.log(bar());

var bar = function() {
 return 'bar';
};

As I mentioned above, function expressions are not hoisted. So the code above will get a TypeError, since bar is not known as a function on that point. One important detail is that, functions are hoisted before variables. The code below will print ‘bar-2’ to console.

console.log(bar());

var bar = function() {
  return 'bar-1';
};

function bar() {
  return 'bar-2';
};

Things to note:

  • Hoisting is per-scope.

Ahmet Kapusuz

Written by Ahmet Kapusuz who lives and works in Amsterdam as a Software Engineer.