But first, let’s explore function scope and its implications.
Consider this code:
bar(..)
has its own scope bubble. So does the global scope, which has just one identifier attached to it: foo
.
Because a
, , c
, and bar
all belong to the scope bubble of foo(..)
, they are not accessible outside of foo(..)
. That is, the following code would all result in ReferenceError
errors, as the identifiers are not available to the global scope:
Function scope encourages the idea that all variables belong to the function, and can be used and reused throughout the entirety of the function (and indeed, accessible even to nested scopes). This design approach can be quite useful, and certainly can make full use of the “dynamic” nature of JavaScript variables to take on values of different types as needed.
On the other hand, if you don’t take careful precautions, variables existing across the entirety of a scope can lead to some unexpected pitfalls.