What is hosting?
Variables and functions are hoisted to the top of their containing scope. In English that means that they’re declared, but not initialized or implemented. Let’s see some code to demonstrate this:
The above will run just fine because greet exists in the global scope and can be accessed within the sayHello function.
Let’s look at another example and see what happens:
What do you think will happen?
The first console.log will return undefined, but the second will return our string “Hello world again from inside the function”. Why is that? It’s because our variables are being hoisted or pushed to the top of our sayHello() function. They’re being declared, but not initialized. Behind the scenes this is what’s going on:
A new greet variable is being declared before any other code is ran inside the function. Since it’s declared and has not been initialized or had anything assigned to it, when we call console.log the first time we receive undefined, but after we initialize it and call console.log a second time we see our string returned to us.
The second is by using a function expression, which simply means assigning a function to a variable:
The declaration of a function expression is hoisted to the top, but not the implementation of it. Calling the two different functions within our earlier example demonstrates this:
The above will return an error because the function has been declared, but not initialized at the top of a scope due to it being a function expression. If we used a function declaration instead, then we could call the function just fine because when function declarations are hoisted they’re also initialized.
Originally published at codeandcomedy.com on September 13, 2015.