Some Background on JavaScript Variables


Introduction.  Since you have seen variables and basic operations on variables in a variety of languages by the time you take this course I will not spend very much time on them.  As is often the case when working in web programming variable definitions are actually much simpler than they are within more client oriented application development languages such as C++, Java or Visual Basic.  Though the variant variable type in Visual Basic is very much like the overall inclusive type declaration we will use in JavaScript.

For code readability and portability you should always declare your variables using the 


keyword whenever you first use a variable.  

The Naming Conventions.  You should always give your variables names that reflect what they hold.  For example, calling something unknown_interest_rate or UnknownInterestRate is much more helpful than i.  There are three basic rules for naming variables.

  1. The initial character must be a letter, but subsequent characters can be letters, numbers, underscores or dashes.
  2. No spaces are allowed in variable names.
  3. Variables are case sensitive!

Arithmetic With Variables.  The arithmetic with variables is pretty standard and I encourage the use of parentheses when you need to ensure the calculation precedents.  The basic operators are contained in the following table.


Operation Symbol
addition +
subtraction -
multiplication *
division /
modulo %
negation -
increment ++
decrement --


Now I will present an example that you should save as SecondsPerDay.html.  This script will also server to illustrate some other basic programming approaches in JavaScript.


<title>Seconds in a Day</title>

<script language="JavaScript">

var SecondsPerMinute = 60;
var MinutesPerHour = 60;
var HoursPerDay = 24;

var SecondsPerDay = SecondsPerMinute*MinutesPerHour*HoursPerDay;


<body bgcolor = "000044" text = "aaaaaa">

<H1>By my calculations</H1>

<font size = 4>
<script language="JavaScript">

var FirstPart = "There are ";
var LastPart = " seconds in a day.";
var WholeThing = FirstPart + SecondsPerDay + LastPart;





This code does very little other than set variables for the number of seconds per minute, the number of minutes per hour, and the number of hours per day and then use them to calculate the number of seconds per day.  It also shows you how to display the results using the write( ) function.

After uploading this page and going to it on your web with a web browser, you should see something like the following.  Notice that I have done a little bit of formatting of the output.