If you don't declare a variable (explicitly creating it in the current scope) using var
, let
or const
then (in non-strict mode) you create an implicit global.
Globals are a fantastic way to have different functions overwriting each other's variables (i.e. they make code a pain to maintain).
If you use var
, the scope of the variable is limited to the current function (and anything inside it — it is possible to nest functions).
(const
and let
scope constants and variables to the current block instead of the function, this usually makes variables even easier to manage than var
does.)
Google Adsense uses globals because it splits scripts into two distinct parts (one local and one remote). A cleaner approach would be to call a function defined in the remote script and pass the parameters as arguments instead of having it pick them up from the global scope.
Modern JS should be written in strict mode which bans implicit globals (preferring to explicitly declare them at the top level instead, thus prevent accidental globals when a variable name is typoed).