Scope
The next critical characteristic of a variable is its scope
: whether it’s local to a specific
function or global to the entire JavaScript application. A variable
with local
scope is
one that’s defined, initialized, and used within a function; when the
function terminates, the variable ceases to exist. A global
variable, on the other hand, can be accessed anywhere
within any JavaScript contained within a web page—whether the JS is
embedded directly in the page or imported through a JavaScript
library.
In Chapter 1, I mentioned that there is no special syntax necessary to specifically define a variable. A variable can be both created and instantiated in the same line of code, and it need not look any different from a typical assignment statement:
num_value = 3.5;
This is a better approach:
var num_value = 3.5;
The difference between the two is the use of the var
keyword.
Though not required, explicitly defining a variable using the
var
keyword is strongly recommended;
doing so with local variables helps prevent collision between local and
global variables of the same name. If a variable is explicitly defined
in a function, its scope is restricted to the function, and any
reference to that variable within the function is understood by both
developer and JavaScript engine to be that local variable. With the
growing popularity of larger, more complex JS libraries, using var
prevents the unexpected side effects created by using what you think is a local variable, only to find out it’s ...
Get Learning JavaScript now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.