- [Instructor] In recent versions,
JavaScript has added a few features
that enable you to control scope without building closures.
ECMAScript 5 implemented the forEach method for arrays.
We can use this method instead of a for loop
to iterate through an array.
Because forEach takes a callback function
as its first argument,
each time through the loop creates a separate local scope.
Essentially, the work of creating a closure
is already built into this method.
So in the updateUIWorking method,
we can recreate our stopwatch simulator
using forEach instead of for
to rewrite our code without a closure.
So I'm going to comment out that whole for loop.
Now, we use forEach with an array, so we need to start
by putting the numbers we want to count through in an array
and then referencing that.
So I'm going to create a variable called count,
and that's an array of zero, one, two, three, four,
five, six, seven, eight, and nine.
And this is just one way of going at it.
And then, we can simply say count.forEach,
using the forEach method on the count variable,
passing in an anonymous function,
and using el to reference each array element
as we iterate through the loop.
And then, I can create my setTimeout function,
passing that an anonymous function,
and I want to do that same
DOM manipulation.
So I'll just copy that in from my earlier code,
uncomment that.
Then, I have to change that j to reference el instead.
And then, finishing up my setTimeout.
Time is going to be 100 times el.
And so this is essentially replacing the outer function
that our existing code used to avoid creating a closure.
So saving this, reloading the page in the browser.
And I do not need to enter anything in the text box
because I have commented out the fetch code here.
So just clicking the button,
and we get the animation just like we did before.
So the timer works just like it did.
ES6 gives us additional options by introducing block scope.
In modern browsers, using the let or const keyword
creates a type of local scope, known as block scope,
when it's used within curly braces other than a function,
like within a for or if statement.
So for instance,
when we're using a var statement within a loop
to create a separate local scope each time,
we have to code up a closure,
but an alternative in ES6
is simply to change the var keyword to let,
taking advantage of block scoping in the for block.
So I'm going to comment out the forEach code we just created,
and then I'm going to uncomment the existing for.
I'm going to comment out the start and end
of the nested function.
I'm going to change my js back to is, here and here.
And then, I'm going to change that var to let.
Saving that work, reloading the browser,
clicking that button.
And again, the functionality is identical.
So using the let keyword saves us some extra work
in a situation like this.