17 Variable Hoisting example

Last updated on July 13th, 2020 at 02:29 pm.

This video is taken from the full course that will teach you HTML, CSS, Programming concepts and Javascript .

Video Transcript:

Hi, and welcome back.

So if I come here to Firefox and then open Scratchpad, I already have this typed out here.

So in this case, you’re seeing that I’m calling ‘x’ and ‘x’ has been declared down here.

So if I run this, it’ll give me ‘x’ is undefined.

And this is an example you are familiar with because you saw the same thing when we were looking at undefined and reference errors in JavaScript.

So if I run this, ok, this is because I already did run this with ‘x’ up there.

So let me change, let me call ‘y’, and then run this.


I also did run ‘y’.

So let’s say I do ‘z’ and I change this to ‘z’ and then I run.

Let me close that and then I run.

You’ll see it gives us undefined.

So the reason the first time I did ‘x’ and said they showed the values of ‘5’ and ‘10’ is because that is the second time I was running this code.

You know that by the second time I’m running the code, these variables are already stored in the memory of the browser.

So even if I run this a second time, and right now if I run this a second time, it’ll give me the value of ‘z’ as ‘5’ because by now, the value of ‘z’ is already stored in the browser.

So if I run it, let me first of all close this undefined.

And if I run this, it’ll give us the value of ‘z’ is equals to ‘5’.

And this is because, the value of ‘z’, by the second time I’m running this code, the value of ‘z’ is a variable that is already stored within the memory of the browser.

So keep that in mind.


So we said that functions are also hoisted.

So this is a simple function and I have it commented out.

This is a simple function that adds ‘3’ and ‘4’.

So in the next video, let’s look at how this function will get hoisted to the top.

I will see you in that next video.

This section is from Learn Javascript from Scratch.

Learn Javascript from Scratch

Comment Here