Instructor: In this lecture,
I'm gonna show you a new way of creating IIFEs
using the concepts that we just learned
in the last lecture.
So, in the last lecture,
we saw that variables declared
using let and const
are block-scoped.
And this means that these variables
are defined inside of a block.
And from the outside of that block,
they are not accessible.
Now, what does that sound like to you?
Yeah, that's data privacy
that we've been talking about a lot
during our big project, right?
So up until this point,
we always used immediately-invoked
function expressions for that.
But it looks like in ES6,
we have a new, much simpler way
of achieving data privacy.
Because all we have to do is to use a block.
So let's see how.
Now a block is not restricted
only to if statements or for loops
or while loops.
So we can also just write a block
like this.
All we have to do is to use curly braces
and then create some code inside of these
and we just created a block.
So let's now create a constant in here.
So const a is one.
And then let's also create b, two,
using a let statement here.
So it doesn't make any difference
thus to use both of them here.
And we now were to console logged
these two here,
console.log let's say a plus b,
then what would we get?
Alright, we have an error here.
And that's because these values
are not accessible from outside of the block.
So again, they're block-scoped
and not function-scoped.
So what we have here now
is exactly like an IIFE, right?
Like an immediately-invoked function expression.
So we created some data here
that is not accessible from the outside.
And it's much easier to write it like this, right?
Remember, an IIFE, in ES5 would be written like this.
So ES5,
we had to do all this work
and write it like this
just to create a simple variable
that's not accessible from the outside.
And then we also have to call this function.
Right?
So if we do console log now,
okay, and let's get rid of that,
then of course we have our error here, right?
So that was the old way.
So this is ES6.
Now, let's just try to add var here, okay?
So var c equals three,
and what's gonna happen then?
And of course you know the answer.
Right?
So again, let's get rid of this.
And now, of course, we see three.
And that's because for variable declarations
with a var keyword,
it doesn't matter if they're inside of a block
or if they're not inside of a block,
because they're not block-scoped.
They're function-scoped.
Alright, so this is a very simple change
that you can do if you wanna start writing ES6 code.
So if you have a simple IIFE like this
that you need to write,
you can very simply switch
to doing it like this.
So this is very simple and very straightforward,
once again.
Alright, so let's now move on
to the next feature of ES6.