HTML and CSS Reference
In-Depth Information
That's not entirely true, actually. Using the var keyword attaches the variable to the nearest closing scope,
so using it outside any function will declare the variable on the global scope as well.
Note that the lack of any block-level scoping can cause bugs that are pretty hard to track down. The simplest
example of this is the use of loop counters; for instance,
for (var i = 0; i < 10; i++) {
console.log(i);
}
console.log(i);
That last logging statement won't output null or undefined , as you might expect. Because of the lack of block
scope, i is still defined and accessible. This can cause problems if you don't explicitly define the value of your loop
counter variables on every reuse.
Global scope is something to be avoided in JavaScript. Not only do you have all the usual reasons, such as
code modularity and namespacing issues, but also JavaScript is a garbage-collected language. Putting everything in
global scope means that nothing ever gets garbage collected. Eventually, you'll run out of memory, and the memory
manager will constantly have to switch things in and out of memory, a situation known as memory thrashing.
Declaration Hoisting
Another concern with variable declarations is that they're automatically hoisted to the top of the current scope. What
do I mean by that? Check this out:
var myHealth = 100;
var decrementHealth = function() {
console.log(myHealth);
var myHealth = myHealth - 1;
};
decrementHealth();
So, you would think that this would
output
100
declare a new, function-scoped variable,
myHealth , shadowing the globally scoped
variable myHealth
set the function-scoped
myHealth to 99
And, it would be totally reasonable to think that. Unfortunately, what you actually output is undefined . JavaScript
will automatically lift the declaration of myHealth to the top of the function, but not the assignment.
After the JavaScript engine gets done with that, here is the code you're actually left with:
var myHealth = 100;
var decrementHealth = function() {
var myHealth;
console.log(myHealth);
myHealth = myHealth-1;
};
 
Search WWH ::




Custom Search