Day of the week

The following code can be placed anywhere in the html file:


/* Sometimes, doing simple things in JavaScript is quite difficult
This code gets the name of the day of the week and prints it */
var d = new Date();
var n = d.getDay();
var weekday=new Array(7);
document.write("<p>Today is <b>" + weekday[n] + "</b></p>");


The code above finds the name of the day of the week and writes it to the document. This seems like a simple task, but JavaScript can only tell us the day number, not the name, so we have to build an array of day names and then use the number as an index to find the correct name.

Notice that we have declared 3 variables in this script. We use "d" to hold a new date object. Then we get the day number from "d" and assign it to "n". The variable "weekday" is used to hold the array of day names.

We then use the document.write method to write the name of the day by accessing the correct name from the "weekday" array, using "n" as the index. For example, if the day number is 3 (the value of n is 3), the day name is Wednesday.

Notice that the comment above this script used the multi-line format, starting with "/*" and closing with "*/", exactly like comments in CSS.