Day of the week

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

<script>

/* 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);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";
document.write("<p>Today is <b>" + weekday[n] + "</b></p>");

</script>

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.