Visible variables and invisible variables
You can define a variable in one of the following ways:
var numberVariable =0;
var stringVariable ="";
var arrayVariable = [];
var objectVariable = {};
// more on objects later
Variables can only be seen inside the code block in which they are defined. This means:
- Global variables: Variables defined outside a function are visible everywhere
- Local variables: Variables defined inside a function can only be seen inside that function
- Local variables: Variables defined inside a loop can only be seen inside that loop
- If you redefine a variable again, the new version of that variable will be seen inside that block, and the old version will still exist outside! ( HolySmokes! )
Global variables
Global variables are typically used by beginners until they figure out function pipelines.
Reading a global variable outside any functions
Global variables are declared at the top of the program outside of the functions.
var testVar = 'foo';
console.log( testVar );
Reading a global variable inside a function
Global variables can be seen inside all program functions.
var testVar = 'foo';
function testFunction() {
console.log( testVar );
}
Local variables
Local variables are a cleaner way to code. Function pipelines use local variables instead of global variables.
Reading a local variable inside a different function
Local variables can only be seen inside the same function in which they are defined. They cannot be seen inside other functions.
function functionOne () {
var testVar = 'foo';
}
function functionTwo () {
console.log( testVar );
}
Check the Javascript console to see what happened...
Reading a local variable that has already been defined globally
Local variables will clobber global variables if redefined.
var testVar = 'foo';
function testFunction() {
var testVar = 'bar'; // yikes - testVar has been redefined
console.log( testVar )
}
Reading a global variable that has been redefined locally
Local variables will clobber global variables if redefined. But the global version will still work, but as a separate variable with the same name! Reusing the same variable names is confusing and should be avoided.
var testVar = 'foo';
testFunction();
console.log( testVar );
function testFunction() {
var testVar = 'bar'; // yikes - testVar has been redefined
}
Reading a local variable that has been redefined inside a programming block
Local variables will behave unpredictably if redefined inside a for
, if
, or then
block.
function testFunction() { // outer code block
var testVar = 'foo';
for (i=1; i<10; i++) { // inner code block
var testVar = 'bar';
}
console.log( testVar );
}