Neticulis.com > Programming > Learning Javascript
>Tutorial Lesson 2:
Creating and modifying Variables

A variable is a container for information, such as numbers, strings, etc.

Before you actually do anything with a variable you should declare it, using the word "var". Lets say I want to create a variable to keep track of someone age, I would do the following:
var age = 35;
This will declare a variable called age, and place the number 35 into it, finally we end the line with a ";". it is good programming practice to not declare a variable more then once, in many other languages it will cause errors, javascript however will ignore it.

So now that I have declared the age variable, and put a number into it, I can do anything I want to it, for instance, multiplying by two:
age *= 2; // Now age will equal 75!
Here we multiply by 2 using the "*=" operator, which could also be written as: age = age * 2;
The first example is just a shorter way to code the same thing. you also may notice the double slashes after we close the line, this is how you can add a comment to your code, anything after the // will be ignored by javascript.

The example above is an integer variable, simple speaking, a whole number.

Other types of variables (with examples) are:
- Floating Point: Any number that is not a whole number, such as 3.12, or 5.9
     var bodyTemp = 98.6;
- Boolean: true or false
     var alive = true;
- String: This can contain letters, numbers, or a combination of both, values must be enclosed by      single ' or double " quotes.
     var name = "Bob";
    var today ="January 4th";
- Arrays: These variables can contain more then on piece of information, including other variables.
     var favoriteFoods = ["Pizza","Spaghetti","Chocolate"];
    var myFriends = ["Joe","Bob","Jim"];
- Objects: These are very powerful variables, that can do nearly anything! The example below is on of the simplest examples I can show you.
     var myCat = {"Name" : "Spot", "Age" : 4, "Hungry" : true};

Dont worry if your confused about some of these at the moment, it will become clear later on when to use each type of variable.




Copyright 2005-2008 Neticulis.com