This is a technique used by the JavaScript engine called hoisting. The parser will read through the entire function before running it, and any variable declarations (i.e. using the var
keyword) will be executed as if they were at the top of the containing scope. So your code behaves like:
var country;
var i;
country = "USA";
switch (country) {
case "USA":
country = i;
case "blach":
//not finished yet
}
i = 10;
So, i
is declared throughout the entire scope, but its value is undefined
until the i = 10
statement runs.
In ECMAScript terms, when a function is invoked, the function's new lexical scope builds its VariableEnvironment
before any of the function's code runs. In ECMAScript 10.5, step 8:
8. For each VariableDeclaration... d in code, in source text order do
a. Let dn be the Identifier in d.
...
i. Call env’s CreateMutableBinding concrete method passing dn and configurableBindings as the arguments.
ii. Call env’s SetMutableBinding concrete method passing dn, undefined
, and strict as the arguments.
This is quite a mouthful, but basically it says:
Before you run a function, look through the function's source code for declarations like var [identifierName]
.
For each declaration you find, create a new variable in the function's scope with the name [identifierName]
used in the declaration and then set its value to undefined