View Full Version : Undifined Variables, a constant issue in my JavaScript programs

01-23-2011, 04:41 AM

I am a newbie at JavaScript programming and I am continuously running into the same error: "the variable is undefined"

In the below js code, I am attempting to write a yearly calendar into an html file. I have followed the instructions from a text, and I am fairly certain that I have followed them correctly. From what I can see the problem is that my calendarDay variable is undefined.

How can I fix this, and better yet prevent it from happening again?

The portion of my JavaScript code that is causing the error is below and once again I really appreciate your feedback ...

/* The purpose of this function is to place a monthly calendar within a larger table cell. */

function writeMonthCell(calendarDay, currentTime) {
document.write("<td class='yearly_months'>");
writeMonth(calendarDay, currentTime);

/* Insert a function named yearly(). The purpose of this function is to write the entire yearly calendar containing all of the seperate monthly calendars as cells within the larger table. The function has a single parameter named calDate. */

function yearly (calDate) {
if (calDate == null) calendarDay = new Date() // loads the current date and time

else calendarDay == new Date (calDate); // first error "calendarDay is not definded"

var currentTime = calendarDay.getTime(); // retrieves the current time in milliseconds

var thisYear = calendarDay.getFullYear(); // retrieves the four digit value for the year

// the following writes the calendar title
document.write("<table id='yearly_table'>");
document.write("<td id='yearly_title' colspan='4'>");

var monthNum = -1; //var monthNum will keep track of the month value being written in the calendar

// the following writes the calendar table
for (var i = 1; i <= 3; i++) {
for (var j = 1; j <=4; j++ ) {
monthNum = monthNum +1;
writeMonthCell(calendarDay, currentTime);

01-23-2011, 05:12 AM
Before you can use a variable, you have to define it using the var keyword. You never define calenderDay.

Be advised, though, that defining a variable within a function only makes it available within that same function. That's why you can use the same variable name in different functions, and they will have nothing to do with each other.

01-23-2011, 11:28 PM
Also, the line

else calendarDay == new Date (calDate)

is evaluating whether calendarDay is equal to new Date (calDate),

which throws an error if calendarDay is not yet defined or calDate is not a proper parameter for Date.