Hello, in this JavaScript video, I am going to show you immediately invoked function expressions. So before we even do that, let me just quickly set up a, a function. So I'm going to set it up like this. So long phone, set it by assigning it to a variable file and anonymous function and equals function. So this is to help prevent variable hoisting. And let me just again, implement this.
And what I'm gonna do a little loop here. So I'm gonna say, var i equals zero. I plus plus, and then we're going to do console dot log. Here, we need to actually run the function. So we Going to Epic song. Save that run it we get zero to nine, it doesn't print out 10 fish left and 10 not less than or equal to one, we'll do console dot log I here I didn't see it prints out 10 because the variable is hoisted to these function curly braces.
So even though I made here, it is accessible outside of here, but it is not accessible, you know anywhere outside of the function itself. If you want to restrict the access of this two, let's say within this as well, what you can do is just do an immediately invoked function expression. And what that is essentially, we do var attic loop equals function Open brackets like that, this will basically immediately call it through the way and now forward to run it. As you can see, it only prints up to nine, but you get an error here. So this is hoisted, still, but to essentially these curly braces, so that's a great way if you want to help eliminate variable hoisting within a function lucky enough away to implement this as well sorry the other way and, of course, epic funk too, we can need leave this name the same color with it in here, that doesn't actually matter.
I think we don't even need it because we don't need the name. Because if we are just gonna immediately invoke the function inside of it and not call yourself we can just implement it like so and this will achieve the exact same result and we get an error here. And I have not learned epic to have a look. printing this one now let's see what I'm missing. Am I missing anything immediately obvious is messing up because you know this line here forward to get rid of this. Alex, he printed out again he basically crashes at that point.
So that's the reason just need to comment that this line and if I were to rerun it, so it's just printing out this loop here. As you can see, it is not defined in epic from two because this variable is technically posted to this function there are not this overall function. So that's the benefit of using immediately invoked function expressions. If you have any questions, feel free to drop me a message and I look forward to seeing you in the next video.