Hoisting

One of the tricky concepts that stumps newcomers to JavaScript is hoisting. Even seasoned developers coming from other languages can be bitten by this feature. In most C based languages developers are used to the concept of block based scoping versus function based scoping. The best way to understand how hoisting works is by example:

function foo() {
    bar()
    baz()
    var bar = function() {
        console.log('Hello')
    }
    function baz() {
        console.log('World')
    }
}

foo()

So we have two different types of hoisting happening here, variable hoisting and function declaration hoisting.

What happens in this case is the variable bar is hoisted to the top of the function body and will return as undefined because at the time of it being called we have not assigned it to anything. Differently, the function baz is hoisted up the entire function body intact, so it will return as expected. So our end result is a TypeError telling us that undefined is not a function.

 
35
Kudos
 
35
Kudos

Now read this

Writing a REST API with Hapi.js

Coming from a Python background, there were a couple of different solutions for web frameworks. Some were more of the “batteries included” persuasion, while others were extremely light weight and required you to piece together different... Continue →