What are Variables and Literals and how can I use them? |
Unlike other programming languages, Javascript variables do not need to
be formally declared. That simply means that you can create a variable
at any time and it will be accessible at any time as well. You create
variables with the var command. For instance, with the examples
above, if you wanted to create a variable called "currenttime" and another
called "result," the Javascript code would be:
var currenttime
var result
So, how can you assign values to a variable? Well, one way would be for
the user to input a value in a text box, for example, and then just read
the value from there (we will go into how to read values from a text box
later.) Another way would be to just to assign it to another variable to
copy the value. The most easiest way, however, would be to assign to a
literal.
So, what's a literal? Well, unlike a variable, whose value changes throughout
the Javascript program, a literal's value remains constant. Examples of
literals include the number 5, the letter B, or the string 'Hello'. Let us
say that we were writing that calculator program mentioned above and we
wanted the program to start the program with the number -1 in the "result"
variable. We could accomplish this in two ways:
var result
result = -1
OR we can combine the two statements into
var result = -1
We will use variables and literals more in later sections.
Home | Go to Top | Next Page |