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
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.
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.