HTML and CSS Reference
In-Depth Information
console.log(j);
j = 10;
}
Intuitively it looks like both of these functions will fail because they are attempting to ac-
cess a variable before it is declared. In fact, when JavaScript functions are executed they
first look for all function scoped variables that will be declared anywhere in the function.
These are then “hoisted” to the top of the function.
These function variables remain undefined until explicitly assigned a value, but they do ex-
ist as undefined variables. Globally defined variables are not hoisted, and therefore the two
functions produce different results:
> testLocal()
undefined
> testGlobal()
ReferenceError: j is not defined
For this reason it is always best practice to declare function scoped variables at the top of
the function, since this is what the language will automatically do anyway.
Search WWH ::




Custom Search