- General Syntax
- Calling Functions
- Arguments
- Returning Values from Functions
- Scope of Variables
- Summary
- Q&A
- Workshop
- Exercises
Scope of Variables
We have already seen how to declare variables with the var keyword. There is a golden rule to remember when using functions:
“Variables declared inside a function only exist inside that function.”
This limitation is known as the scope of the variable. Let’s see an example:
// Define our function addTax() function addTax(subtotal, taxRate) { var total = subtotal * (1 + (taxRate/100)); return total; } // now let's call the function var invoiceValue = addTax(50, 10); alert(invoiceValue); // works correctly alert(total); // doesn't work
If we run this code, we first see an alert() dialog with the value of the variable invoiceValue (which should be 55 but in fact will probably be something like 55.000000001 as we have not asked JavaScript to round the result).
We will not, however, then see an alert() dialog containing the value of the variable total. Instead, JavaScript simply produces an error. Whether you see this error reported depends on your browser settings—we learn more about error handling later in the book—but JavaScript will be unable to display an alert() dialog with the value of your variable total.
This is because we placed the declaration of the variable total inside the addTax() function. Outside the function the variable total simply doesn’t exist (or, as JavaScript puts it, “is not defined”). We used the return keyword to pass back just the value stored in the variable total, and that value we then stored in another variable, invoice.
We refer to variables declared inside a function definition as being local variables, that is, local to that function. Variables declared outside any function are known as global variables. To add a little more confusion, local and global variables can have the same name, but still be different variables!
The range of situations where a variable is defined is known as the scope of the variable—we can refer to a variable as having local scope or global scope.