Creating JavaScript Functions

A function is a series of commands that either performs an action or calculates a value. A function consists of the function name, which identifies it; parameters, which are values sent to the function; and a set of commands that are run when the function is used. Not all functions require parameters. Two things to remember about functions. One, functions are case-sensitive. XMAS and xmas are considered different function names. Second, a function name must begin with a letter or underscore (_) and cannot contain any spaces. Where you place a function in the HTML file is important. The function definition must be placed before the command that calls the function. Although not a requirement, most programmers place the function definitions between the <HEAD> and </HEAD> tags. You're now going to start creating a function called XmasDays, which will calculate the number of days remaining until Christmas, given the current date.

Before creating the function, consider how to calculate the number of days remaining until Christmas. Again, we are going to assume that todays date is October 15th. The first thing we will do is calculate this date against the 25th. The mathematical formula used would be (25-15). You must also add the number of days in October and November to the total. October has 31 days, and November has 30 days. This means that the number of days between October 15th and December 25th is:

(25-15) + 31 + 30=10 + 61 = 71 days

Your simple version of the XmasDays function will handle only dates in October. Notice in the code below you will add the comment (which is seen after the //) "this function calculates the number of days until Christmas," which performs no task other than to let you know what the function does.

You will place this code after your title tag in your heading section of your document and just above the ending head tag (</HEAD>. The code for this reduced function is as follows:


<!--Hide from non-JavaScript browsers

//This function calculates the number of days until Christmas

function XmasDays(Month, Day, Year) {

var DayCount=(25-Day) + 31 + 30;

return DayCount;


//Stop hiding-->


Now you must call the XmasDays function.

Scroll down to the line "var DaysLeft=999;" and replace this line with:

var DaysLeft=XmasDays(ThisMonth, ThisDay, ThisYear);

Just Plain Stupid