Introduction to Javascript for Non-Nerds


What are Variables and Literals and how can I use them?

What are Variables and Literals and how can I use them?

If you have done any programming before, then you should be very familiar with variables and literals. A variable is basically a value that you create that is changed during the course of your Javascript program (i.e. it varies). For example, let's say you were creating a Javascript program to display a clock. You would have to store the current time in some type of value that would constantly change. Or let's say you were creating a Calculator program. You would need a place to store the numbers entered and the resulting values.

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.
HomeGo to Top Next Page