A variable is a named element in a program that stores information. You can create (or declare) variables with any of the following commands:
where variable is the name of the variable, and value is the initial value of the variable. A variable name must start with a letter or underscore ("_") and consist of digits (0-9), letters (A-Z, a-z), the underscore symbols ("_") or the dollar sign ("$"). The first command above creates the variable without assigning it a value, the second and the third commands both create the variable and assign a value to it.
If a variable is defined outside of any function, it is called a global variable and is accessible everywhere in the current document. A variable declared within a function is called local and its scope is limited to the current function. Using the key word var is optional, but it is required to use by declaring a local variable if it has the same name as some global one.
If a variable is used without declaring it with a keyword var, or is declared but not initialized, it gets a special value null.
Examples:
var Month; var ThisDay; ThisDay = "Friday"; |
JavaScript supports for different types of variables:
A numeric variable can be any number, such as 16, 2.75, or -5.6.
A string variable is any group of characters, such as "Hello", "Submit".
Boolean variables are those that take on one of two values, either true or false. These variables are usually used in the conditional statements (to be covered later).
A null variable is a variable that has no value at all. This happens e.g. when you've created a variable in the program, but have not assigned it a value yet.