Variables

Variables are "basically named buckets of data"[1]. When you refer to a variable by the name, the value it stores is provided to the running code in place of the name. Name a variable using numbers, letters, $ or _; it cannot begin with a number.

Variables in programming are somewhat similar to variables in algebra in small, simple single statement examples. In reality, a variable in a programming language is like a box- you can use it to store things like numbers, strings, object references, and boolean (true or false values). 1 and 3.147 are numbers (and '1' and "3.147" are Strings). See String for more on Strings. Objects are things like body (as in document.body...) and the nodes returned by document.getElementById(). Variables don't actually store the object itself but, rather, a reference to the object. Variables are generally changed with assignment statements, using the = operator.

It is possible to have one variable used in different parts of the program and this is bad if the programmer isn't careful or doesn't even know what else is changing his variable. The language provides the keyword var to help with this. var will create a new variable - even with another variable of the same name existing. Once a variable is declared with the var keyword, references to the new variable will refer to the new variable in that variable's "scope". How this works is beyond the scope of the course but when you declare your variables, use the var keyword. Also, w3schools.com has some information on this.

Variable Pointers:

Examples:

Declaring some variables and alerting them

The code
<script type="text/javascript">
function declareAndAlert(){
var num=1;
var name='bob';
var object=document.getElementById('cit1');

alert(num);
alert(name);
alert('name');//drop the quotes if you want the value
alert('Ack- the next should be odd (you would not ever do it)....');
alert(object);
}
</script>
<button onclick="declareAndAlert()">Declare and Alert Values</button>
The button to execute:


[1] http://oreilly.com/javascript/excerpts/learning-javascript/javascript-datatypes-variables.html accessed 6/21/11

Back to Knowledge Dump