AlfieWebDevTips Homefor new and experienced developers
[Home Home] [Web Development Web Development ] [Code Generators Code Generators ] [Resources Resources ] [Contact Us Contact ] |WebDevTips Privacy Privacy |
Print This Page

You are here : Home - Web Development - Javascript - Getting Started - Variables

Variables



A variable is basically a name given to a piece of information we want to store for later use. A variable can be numbers(numeric) or a string (Alpha/Numeric - characters and numbers.) A variable can remain with its initial value or changed to a different value depending on your needs.

Some of you might remember maths questions like this. If x=5 and y=10 what is x+y? x and y are variables so the next question might be something like : if we change x to 8 what is x+y? and so on.

Using variables in javascript allows us to reuse functions by using variables. There are 2 types of variables you can use, these are

  • Global - Global variables are normally declared at the start of your script and can be used and changed within functions
  • Local - Local variables are variables that are declared in a function, these variables will only be used within the function and discarded when the function exits.

As mentioned before, variables can be numeric or alpha/numeric. Each variable you wish to declare(set) must have a unique name. Try to give the variables appropriate names as it makes for easier maintenance. Here is how we declare variables.

Numeric
var apples = 10;
can also be written as
apples = 10;
Both work fine but I would suggest using var apples = 10;
Alpha/Numeric
var applecolor = "Green";
can also be written as
applecolor = "Green";
Both work fine but I would suggest using var applecolor = "Green";
Notice this time that the value of the variable is in "" By using "" we are declaring the variable as a string.
Differences

If we set var apples = 10; then we could do some maths to add or take away apples using apples+=5; so the variable apples would now be 15

However, if we had set var apples ="10"; then done the maths as above apples+=5; then, because we declared apples as a string by using "", the maths doesn't work. Its simply adds the 5 to the end of the string so the variable apples would now be 105

Sounds simple but it really is important to make sure you declare variables properly or you could end up with some strange results.

As promised in the previous chapter, we can now look at using functions with variables.




16 Nov 2003




Google
 

[back to top of page]   

[labelled with icra -  - this link will open in a new window] [RSS Content]

[Copyright © WebDevTips]