Java Reference
In-Depth Information
sCope and lifetime
What is meant by scope ? Well, put simply, it's the scope or extent of a variable's or function's
availability—which parts of your code can access a variable and the data it contains. Scope is
important to any programming language—even more so in JavaScript—so it's imperative that you
understand how scope works in JavaScript.
global scope
Any variables or functions declared outside of a function will be available to all JavaScript code on
the page, whether that code is inside a function or otherwise—we call this global scope . Look at the
following example:
var degFahren = 12;
function convertToCentigrade() {
var degCent = 5/9 * (degFahren - 32);
return degCent;
}
In this code, the degFahren variable is a global variable because it is created outside of a function,
and because it is global, it can be used anywhere in the page. The convertToCentigrade() function
accesses the degFahren variable, using it as part of the calculation to convert Fahrenheit to
centigrade.
This also means you can change the value of a global variable, and the following code does just that:
var degFahren = 12;
function convertToCentigrade() {
degFahren = 20;
var degCent = 5/9 * (degFahren - 32);
return degCent;
}
This new line of code changes the value of degFahren to 20 ; so the original value of 12
is no longer used in the calculation. This change in value isn't seen only inside of the
convertToCentigrade() function. The degFahren variable is a global variable, and thus its value
is 20 everywhere it is used.
Additionally, the covertToCentigrade() function is a global function because it is defined outside
of another function (yes, you can create a function within a function . . . funception!), and they too
can be accessed anywhere in the page.
In practice, you want to avoid creating global variables and functions because they can be easily
and unintentionally modified. You can use some tricks to avoid globals, and you will see them
throughout this topic, but they all boil down to creating variables and functions in functional
scope.
 
Search WWH ::




Custom Search