How to get day of the week in JavaScript using getDay()
The JavaScript getDay() method is beneficial to work with the days of the week. This shot will discuss how to get the day of the week using this method.
Syntax
The getDate() method can only be used with the Date object instance. This means that to use it, we must first create a date object.
let date = new Date();
date.getDate();
Parameter
The getDay() method requires no parameter.
Return value
The getDay() returns a value within the range of zero to six, a zero-based numbering. The value returned represents a day of the week. Hence, 0 represents Sunday, 1 represents Monday, and so on.
Example of how to get the day of the week
- First, we create an array of the days of the week:
let days = ["Sunday", "Monday", "Tuesday", "Wednesday","Thursday", "Friday","Saturday"]
- The array above will be looped using the
forEach()method. Then we will pass two parameters, the day parameter, and index. Thus thedayparameter represents all of the days in the array, and theindexrepresents its corresponding position in the array.
days.forEach((day,index)=>{// loop body})
- Finally, as we loop the
daysarray, we will check if the day index is equal to the value returned by thegetDay()method. If the values are the same, then the day of the week will be logged to the console.
if(index == new Date().getDay()){console.log("Today is "+day)}
Final code
The final code is below:
let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]days.forEach((day,index)=>{// Check if the index of day value is equal to the returned value of getDay()if(index == new Date().getDay()){console.log("Today is "+day)}})
Thanks for reading! π