- [Instructor] Hoisting is often misunderstood
so let's focus some time on this mysterious word
and what does it mean.
In short, hoisting is JavaScript's behavior
of moving all declarations to the top of its scope.
When you declare a variable at the bottom of your file
it will be hosted or moved to the top of its scope
when the code is compiled.
Let me demonstrate with some code.
I'm gonna put some notes here so you understand
what's happening.
Let's remove the declaration here and simply define
what warrior is here.
We need to declare it somewhere.
Warrior is defined here.
Then, let's put a note here.
And this is for closure, so I'm gonna write
a note here for you guys.
Wrap in a function now is a closure, there you go.
Let's declare our warrior way below, down here.
What I'm gonna do is leave those two here
and then do a console.log for warrior and warrior3.
But the third warrior hasn't been declared yet,
so let's go ahead and first declare this warrior.
Let's do a var warrior.
So, warrior is declared here.
In theory, if you understand the theory
of JavaScript, everything runs in order.
If I'm declaring warrior here and it's defined up there,
it shouldn't work, but that's what hoisting is.
Hosting, actually because you're declaring something,
without initializing it right away, it's moved
to the top and then its value is assigned here
and then it would work.
This is what hosting is.
If I did something like,
if I'm doing var warrior3 = Viking here,
it will show undefined.
The reason being, is because I am initializing
the value as well as declaring.
So, if I'm declaring first and then it's assigned here,
the value's assigned here, then it's gonna work.
This is what hoisting is.
Hoisting, if you declare anything at the bottom,
if you declare a function way below
and then actually run it at the top,
it's going to work.
This is what hoisting is.
Let's go ahead and actually remove that one here.
And save this and see this in action.
Let's go to our browser and I'm showing Ninja Samurai,
as expected, so this is the first function here.
The console.log that we're seeing here, so Ninja Samurai.
Then we have another console.log,
which is supposed to show me Ninja and the warrior3, Viking.
If we go here we see Ninja and then undefined.
That isn't working.
So, if I went back to my code and instead
of initializing my variable here, I would simply assign it
at the top, but actually declare it at the bottom.
So, let's change this, let me just do a copy and paste
of this at the top.
And then remove the assignment,
since we're doing it here and save this.
Then go back to our browser, now I'm seeing Viking.
This is all due because of hoisting.
Hosting actually grabs that declaration
and looks for an assignment and because it's done
at the top it's gonna work because this
has been already pushed to the top, because of hoisting.
All right, so let's move on.