Variable Scope
The scope of a variable is the region of your program source code in which it is defined. A global variable has global scope; it is defined everywhere in your JavaScript code. On the other hand, variables declared within a function are defined only within the body of the function. They are local variables and have local scope. Function parameters also count as local variables and are defined only within the body of the function.
Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable:
varscope="global";// Declare a global variablefunctioncheckscope(){varscope="local";// Declare a local variable with the same namereturnscope;// Return the local value, not the global one}checkscope()// => "local"
Although you can get away with not using the var statement when you write code in the
global scope, you must always use var to declare local variables. Consider
what happens if you don’t:
scope="global";// Declare a global variable, even without var.functioncheckscope2(){scope="local";// Oops! We just changed the global variable.myscope="local";// This implicitly declares a new global variable.return[scope,myscope];// Return two values.}checkscope2()// => ["local", "local"]: has side effects!scope// => "local": global variable has changed.myscope// => ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access