Variables are "containers" for storing information:
Do You Remember Algebra From School?
Do you remember algebra from school? x=5, y=6, z=x+y
Do you remember that a letter (like x) could be used to hold a value (like 5), and that you could use the information above to calculate the value of z to be 11?
These letters are called variables, and variables can be used to hold values (x=5) or expressions (z=x+y).
|Think of variables as names or labels given to values.|
A variable can have a short name, like x, or a more descriptive name, like carname.
- Variable names are case sensitive (y and Y are two different variables)
- Variable names must begin with a letter, the $ character, or the underscore character
After the declaration shown above, the variable is empty (it has no value yet).
To assign a value to the variable, use the equal (=) sign:
However, you can also assign a value to the variable when you declare it:
After the execution of the statement above, the carname will hold the value Volvo.
When you assign a text value to a variable, put double or single quotes around the value.
When you assign a numeric value to a variable, do not put quotes around the value (if you put quotes around a numeric value, it will be treated as text).
You can have local variables with the same name in different functions, because local variables are only recognized by the function in which they are declared.
Local variables are deleted as soon as the function is completed.
You will learn more about functions in a later chapter of this tutorial.
Variables declared outside a function, become GLOBAL, and all scripts and functions on the web page can access it.
Global variables are deleted when you close the page.
If you assign values to variables that have not yet been declared, the variables will automatically be declared as global variables.
will declare the variable carname as a global variable (if it does not already exist).
You will learn more about the operators that can be used in a later chapter of this tutorial.