- [Instructor] Hoisting is always a subject
that is confusing for newcomers,
so let's explore this a bit and how it relates to classes.
So the best way to demonstrate this in our code here
is to literally copy lines 13 through 16
and use it above the class.
So let's do that.
So let's copy these.
So command C,
and then come at those by doing command forward slash,
and let's put it above class Car,
like so.
So if we save this and then we go back to our Sandbox here,
you'll see that Uncaught ReferenceError: Car is not defined.
So if the class Car would be hoisted to the top
we wouldn't have a problem with this.
So you will always have to define or declare your class
before you actually use it.
So let's remove this code here.
And let's bring these back by doing command forward slash,
save, let's go back to our Sandbox,
and everything is back to normal.
The hoisting works for functions.
So let's say for example, I'm creating
a function here that says hi.
And that will literally return a log
that says Hello this function can be called anywhere!
So we've defined the function so we're good to go here.
So if it worked the same way a class would work
I wouldn't be able to call this function above.
So let's go ahead and do that.
So let's go and run that function right here.
So sayHi, run it there, and save,
and go back to our JavaScript Sandbox
and we don't have any issues.
That means the function is hoisted to the top.
And once it's running it's already there,
ready to be used by our JavaScript file.
So we could literally put that function anywhere
in this file and it would still work.
We could put it here as well and it would work,
because that function once the code is compiled
by the JavaScript engine the engine
will place that code to the top,
then be able to run these functions.
So if we go back here it's run at the top
and then after everything has been compiled.
So this is what hoisting is.
So basically for classes you need to declare them first
before you actually use them.
But for variables, for functions,
you can actually declare them before or after
and use them anywhere in your code and you will be fine.