Go ahead and take a look at this code, and look at what line three is going to alert when FN is invoked. What you probably think is going to happen is we define the variable in the global scope called "MyVariable" and set it to equal or at our value.
Then, we define another variable in the global scope called "FN," that's a function. When this function gets invoked, we go ahead and alert MyVariable. It's not going to find a MyVariable in this scope, it's going to go to its outer scope, and then, learn outer variable. After that happens, it's going to define a variable in FN scope instead of equal to new local value.
You'll notice here, my variable's the same, but what actually happens is this declaration right here was hoisted up to the top of this function. We define a new variable called MyVariable, we alert MyVariable, and it's currently undefined, and then, we set MyVariable equal to new local value. That's the reason why, when we run this code up here, we get undefined.
Now, let's talk about function hoisting. There are two main ways to define a function. The first one is with function declarations, which looks something like this, and the second one is with function expressions. Technically, this is an anonymous function expression, but for this video, I'm just going to refer to it as a function expression.
Down here, we have our function declaration, and again, go ahead and reason about what you think this code is going to do when line 10 runs. Line 10 is going to alert the result of invoking our Foo function. What you think would happen is inside of Foo, we define another function called "Bar," and then, we return the result of Bar.
What happens is the first bar is hoisted, the second bar is hoisted, and then, we return the result of invoking Bar, which gives us two, and then, we alert two. Now, let's talk about function expressions. Remember, this is a function declaration, and this is an anonymous auction expression.
Again, here, we have our code. We have a function Foo. Inside of that function, we define another function, Bar, that returns one. We return the result of invoking Bar, and then, we define another function called "Bar," which returns two. Let's see what this one returns. With this one, we get one, and that's closer to what we would expect to happen.
Because what happens, if you remember back to variable hoisting, the variables here that are declared are hoisted to the top of the functions. That's really all we are doing with this anonymous function expression, we are taking an anonymous function and assigning it to a variable.
Those variable declarations are hoisted. We then get the initialization that is not hoisted, and then, we return the result of invoking Bar, which will give us one.