Block-scoped variables solve this problem for us without the extra hassle of requiring
a function to create a new scope for us. This example is simplified greatly with the use
of block-scoped variables:
for
(
let
i
=
5
;
i
>
0
;
i
--
) {
setTimeout
(
function
() {
console
.
log
(
i
===
0
?
"go!"
:
i
);
}, (
5
-
i
)
*
1000
);
}
Note that we use the
let
keyword inside the
for
loop arguments. If we put it outside
the
for
loop, we’d have the same problem as before. Using the
let
keyword in this
way signals to JavaScript that at each step of the loop, there is to be a new, independ‐
ent copy of the
i
variable. So when the functions passed to
setTimeout
execute in the
future, they’re each receiving their value from a variable in its own scope.
Function Variables
If you’re new to programming, you might want to pour another cup of coffee and sit
up straight: this section is something beginners often struggle with, but is one of the
most important concepts to wrap your head around.
It’s easy enough to think of numbers, strings, and even arrays as variables; it leads us
to this comfortable idea that a variable is a bit of data (or a collection of data in the
case of an array or object). Thinking about variables this way, however, makes it more
difficult to realize the full potential of functions, because you can pass a function
around just as if it were any other variable. Because functions are active, we don’t
think about them as bits of data (which we consider to be passive). And it’s true, a
function is active when it’s invoked. Before it’s invoked, however…it’s passive just like
any other variable.
Here’s an analogy that might help you. If you go to the supermarket, you can think of
fruit as bits of data: 2 bananas, 1 apple, and so on. You decide that you’d like to make a
smoothie with your fruit, so you buy a blender as well. A blender is more like a func‐
tion: it does something (namely, converts fruit into delicious smoothies). But when
the blender is in your basket—not plugged in, not actively blending—it is just
another item in your cart, and you can do the same things with it as you do with your
fruit: move it from the cart to the conveyor belt, pay for it, put it in a shopping bag,
take it home, and so on. It’s only when you plug it in and put fruit into it and turn it
on that it becomes something different than the fruit.
So a function can be used wherever a variable is used, but what does that mean? In
particular, it means you can do the following things:
• Alias a function by creating a variable that points to it.
• Put functions in an array (possibly mixed with other types of data).
Function Variables | 191