MCCC CIS 177 - Markup Languages

Programming with JavaScript

Variables and Data

Types of variables

For a script to be useful, it needs to actually do something other than just output text strings. To have the script determine the date, you need to declare a variable. For example, you can declare a variable named "year" to store the value of the current year. You can then use the variable elsewhere in your program. To declare a variable and assign a value to it, then display the value use the following syntax:

Year=2003;

document.write(Year); or

document.write("The year is " + Year);

Of course, this method isn't all that useful because you need to edit the code when the year changes. In order to know how to have the script get the current value for you, it is important to understand the four types of variables you can use: numeric, string, Boolean, null.

Numeric variables can be any number. String variables are any groups of characters and must be enclosed in single or double quotes. Boolean variables accept either true or false values and are used for branching. Null variables have no value, however, when the script assigns a value, they fall into one of the other three types.

Declaring a variable

Before you can use a variable, you need to declare it with the var command or by assigning a variable a value. For example:

var Month;
var Month = "December";
Month = "December";

It is far easier to troubleshoot code if you explicitly declare a variable using the var command.

Work with Dates

JavaScript does not provide a date data type like other programming languages, however, you can create a date object, which contains date information:

variable = new Date("month, day, year, hours:minutes:seconds");
SomeDay = new Date("November, 3, 2003, 12:15:00");

or

variable = new Date(year, month, day, hours, minutes, seconds);
SomeDay = new Date(2003, 10, 3, 12, 15, 0);

The first example is a string, while the second example uses numeric values. Note that the month is 1 less than the current month because JavaScript numbers the months 0 - 11. Hours are expressed as military time. If you omit the date and time information, the script will return the system's date and time.

Today = new Date();

The above, however, is not enough because JavaScript stores dates and times as the number of milliseconds since 6 pm on 12/31/1969, which isn't very useful. Fortunately, you can use the JavaScript date methods to translate the numbers into useful dates. For each part of the date you want displayed, you need a date method to retrieve the value.

Retrieve date values

To retrieve the date value, you might use the ThisDay variable to store the day of the month, the ThisMonth variable to store the month and the ThisYear variable to store the year. To get that information, you apply the applicable method to each of your variables:

var Today = new Date();

Day:

DayValue = DateObject.getDate(); as
ThisDay = Today.getDate();

Month:

MonthValue = DateObject.getMonth() + 1; as
ThisMonth = Today.getMonth() + 1;

Year:

YearValue = DateObject.getYear(); as
ThisYear = Today.getYear(); // For 2 digit year prior to 2000 and 4 digit year after or
ThisYear = Today.getFullYear(); //For 4 digit year - needed for correct calculations!

Other methods:

getSeconds();
getMinutes();
getHours();
getDay();

Work with Dates

Edit the npntxt.htm to add the following code:

<script language="JavaScript">
<!-- Hide from old browsers

var Today=new Date("November 3, 2003"); // Test date
var ThisDay=Today.getDate();
var ThisMonth=Today.getMonth()+1;
var ThisYear=Today.getFullYear();
var DaysLeft=52; // Test value, will have the script calculate later
document.write("Today is "+ThisMonth+"/"+ThisDay+"/"+ThisYear+"<br>");
document.write("Only "+DaysLeft+" days until Christmas");
// Stop hiding -->
</script>

Expressions and Operators

Expressions are commands that assign values to variables, such as DaysLeft=52. Expressions are created using variables, values and operators, which are elements that perform actions within the expression. A commonly used operator is the + operator, which you used in the previous example to combine elements.

Arithmetic operators

The + operator is one of many arithmetic operators. Others are - (binary subtraction), * (binary multiplication), / (binary division), % (binary remainder of division), ++ (unary increment), -- (unary decrement) and - (unary change sign). Binary operators work on two elements in an expression. Unary operators work on only one variable. Examples:

var Men = 20;
var Women = 25:
var TotalPeople = Men + Women // adds the variables

var Price = 1000;
var Expense = 750;
var Profit = Price - Expense; // subtracts Expense from Profit

var Width = 50;
var Length = 25;
var Area = Width * Length; // multiplies the variables

var People = 50;
var TotalCost = 200;
var CostperPerson = TotalCost / People // divides TotalCost by People

var TotalEggs = 64;
var CartonSize = 12;
var EggsLeft = TotalEggs % CartonSize; // calculates the remainder

var Eggs = 12;
var BakersDozen = Eggs++; // adds one to Eggs

var Eggs = 12;
var EggsIfOneIsBroken = Eggs--; //subtracts one from Eggs

var MyGain = 50;
var YourLoss = -MyGain; // changes the sign

Assignment operators

Expressions assign values using assignment operators, such as =, +=, -=, *=, /=, %=. Examples:

x = y;
x += y; // equivalent to x = x + y
x -= y; // equivalent to x = x - y
x *= y; // equivalent to x = x * y
x /= y; // equivalent to x = x / y
x % y; // equivalent to x = x % y

poem = "Twas the night before Christmas and all through the house ";
poem += "not a creature was stirring, not even a mouse. ";
poem += "All the children were nestled, all snug in their beds ";
poem += "while visions of sugar plums danced in their heads. ";

The math object and math methods

Using math methods is another way to perform calculations. Math methods are applied to math objects:

value = Math.method(variable); as

AbsValue = Math.abs(NumVar); // returns absolute value
SinValue = Math.sin(NumVar); // returns sine, where NumVar is an angle in radians
CosValue = Math.cos(NumVar); // returns cosine wher NumVar is an angle in radians
RoundValue = Math.round(NumVar); // rounds to nearest integer
CeilValue = Math.ceil(NumVar); // rounds up to next highest integer
FloorValue = Math.floor(NumVar); // rounds down to next lowest integer
RandValue = Math.random() // returns random number between 0 and 1

JavaScript Functions

You can use all JavaScript expressions and operators to create custom functions. A function is a series of commands that performs an action or calculates a value. A function consists of a function name that identifies it; parameters, which are values used by the function and a set of commands that run when the function is called. Not all functions require parameters:

function function_name(parameters) {
     JavaScript commands
}

Perform an action with a function

A common action is to display the date using a function:

Define the function:

function ShowDate(date) {
     document.write("Today is " + date + "<br>");
}

Call the function:

var Today = "11/03/03";
ShowDate(Today);

Return a value from a function

You can also use functions to calculate values by using the return command:

function Area(Width, Length) {
     var Size = Width * Length;
     return Size;
}

Call the function:

var x = 8;
var y = 6;
var z = Area(x,y);

Place a function in an HTML file

Placement of th function in the HTML document is important. The function definition must be before the command that calls it. It's common to place the function definitions in the <head> section, while the calling commands are in the <body>. If you want to use the function in multiple HTML documents, it's best to write the function in a separate file and create a link to it in the <head> section:

<script src="URL language="JavaScript"></script>

Create XmasDays Function

Download work in progress or open the npntxt.htm from your disk.

Edit npntxt.htm and insert the following code just below the <title> tag:

<script language="JavaScript">
<!-- Hide from old browsers

function XmasDays(CurrentDay) {
     var XYear = CurrentDay.getFullYear();
     var XDay = new Date ("December, 25, 2003"); //Xmas day initial value
     XDay.setFullYear(XYear); //set current year of Xmas day
     var DayCount = (XDay - CurrentDay) / (1000 * 60 * 60 * 24); // convert ms
     DayCount = Math.round(DayCount);
return DayCount;
}
// Stop hiding -->
</script>

Edit the original script as follows:

var DaysLeft = XmasDays(Today);

Save and view in the browser.