It takes all
var declaration to the top of its scope and this is called variable hoisting.
Why we should learn Hoisting?
Because it will create a lot of unexpected behaviour during execution. On my previous posts, we looked into Closures and how they create a local scope whenever you declare a function. Let's take a look at this example to see how Hoisting breaks that rule when you don't declare the variable with
notice we haven't used
var keyword in front of declaration
bar declaration. On the above example, one level up to
foo() scope is global scope. If it can't find in its parent scope it automatically declares your variable with
var keyword like,
What happens to
const keywords of ES6? Do they get hoisted? For that let's see what they output if you just declare them and don't assign a value same like what the
var variables gets hoisted.
the fact that both the variables are available to
console.log proves that they too get hoisted. But in the case of
const, it is different. Declaring
const variable before its initialization. So yes, they too gets hoisted.
To keep the post small and concise, I am splitting variable and function hoisting into two posts.