I have been wondering for a while if I can use a variable in JS before it is defined, such as the following:
var country = "USA";
switch (country) {
case "USA":
country = i;
case "blach":
//not finished yet
}
/*
put a whole
bunch more code here
*/
var i = 10;
Is this valid? Is it allowed? And if so, what is the technical term for it?
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:So,
i
is declared throughout the entire scope, but its value isundefined
until thei = 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:This is quite a mouthful, but basically it says:
It's called variable hoisting, and it's a good concept to understand as it can occasionally create bugs that are hard to track down.
For example:
The first
console.log
outputsundefined
because the varstuff
in the function was hoisted to the top of the function.Without knowledge of variable hoisting, this result may be confusing.
For this reason, if you look at professionally developed JavaScript code, typically you'll see all variables in a function are declared at the top.
The guys answers are correct. for your example however it is worth noting that
country
isundefined
. as aspillers has mentioned your code behaves as belowbut when your
case
statement ran for "USA",i
was undefined so this was assigned tocountry
. try it here in this fiddle.I guess that you just need to be aware that although the variable declarations are hoisted, the value assignments aren't.
Yes. In JavaScript, variables are hoisted