Submitted by: Submitted by sepi22
Views: 175
Words: 1447
Pages: 6
Category: English Composition
Date Submitted: 08/16/2012 07:40 AM
JavaScript Variables
As with algebra, JavaScript variables are used to hold values or expressions.
A variable can have a short name, like x, or a more descriptive name, like carname.
Rules for JavaScript variable names:
* 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
Note: Because JavaScript is case-sensitive, variable names are case-sensitive.
Declaring (Creating) JavaScript Variables
Creating a variable in JavaScript is most often referred to as "declaring" a variable.
You declare JavaScript variables with the var keyword:
var carname;
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:
carname="Volvo";
However, you can also assign a value to the variable when you declare it:
var carname="Volvo";
After the execution of the statement above, the carname will hold the value Volvo.
To write the value inside an HTML element, simply refer to it by using it's variable name:
Example
var carname="Volvo";
document.getElementById("myP").innerHTML=carname;
Note: When you assign a text value to a variable, put quotes around the value.
Note: 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.
Note: If you redeclare a JavaScript variable, it will not lose its value
Local JavaScript Variables
A variable declared within a JavaScript function becomes LOCAL and can only be accessed within that function. (the variable has local scope).
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.
Global JavaScript Variables
Variables declared outside a function, become GLOBAL, and all...