In the previous articles we learnt the use of JavaScript Date object to get the current Date. Now you will learn to get the Day of week with Day name using JavaScript Array object.
Here JavaScript Array will be used to store the names of 7 days of week at 7 indexes of array object. If you have no idea about JavaScript Arrays then you can learn it from the article: JavaScript Array.
Get Day of Week Example using JavaScript Array
var dayOfWeek = new Array();
dayOfWeek[0] = "Sunday";
dayOfWeek[1] = "Monday";
dayOfWeek[2] = "Tuesday";
dayOfWeek[3] = "Wednesday";
dayOfWeek[4] = "Thursday";
dayOfWeek[5] = "Friday";
dayOfWeek[6] = "Saturday";
// Date object defined with new keyword.
var myDate = new Date();
document.write("Today is: " + dayOfWeek[myDate.getDay()]);
In the above example notice the array indexes from 0 to 6 starting from Sunday to Saturday. This sequence is used to store the Sunday at 0th index of array, Monday at 1st index of array and so on to Saturday at 6th index of array. This sequence perfectly suits the output day number returned by the JavaScript getDay function that returns 0 for Sunday, 1 for Monday and so on. That’s why the combination of array and Date Object results in retrieving the Day of week stored at the Array index from 0 to 6. You can retrieve the day of week by passing the value returned by the getDay function as an Array index e.g. dayOfWeek[myDate.getDay()] that will retrieve the name of the current Day of week.
Continue to next tutorial: JavaScript Month of Year using Array to learn how to get the month name using JavaScript Date functions.