Clarifying: JavaScript Variable Scope

JavaScript: The Definitive Guide, 6th Edition by David Flanagan

3.10 Variable Scope

p53

variable scope/scope of a variable: region of the program source code where the variable is defined

global variable: defined everywhere in JScript code; has global scope

local variable: declared within a function and defined only within the body of the function; local scope

function parameter:  count as a local variable

QUESTION: “Defined” here means ‘to have a value’ ?

  • “Within the body of a function , a local variable takes precedence over a global variable with the same name”; the global variable is ‘hidden’

Example 1: 

var scope = "global";      // Declare a global variable 
function checkscope() { 
    var scope = "local";   // Declare a local variable with the same name 
    return scope;          // Return the local value, not the global one 
}
checkscope()               // => "local" 

 

Example 2: What happens when you don’t use var to declare local variables

scope = "global";             //Declare a global variable, even without var 
function checkscope2() {
    scope = "local";          // 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                       // => "local": global namespace cluttered up 

So, always use var to declare local variables.

 

 

 

One thought on “Clarifying: JavaScript Variable Scope

Leave a comment