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.
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();
The getDay()
method requires no parameter.
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.
let days = ["Sunday", "Monday", "Tuesday", "Wednesday","Thursday", "Friday","Saturday"]
forEach()
method. Then we will pass two parameters, the day parameter, and index. Thus the day
parameter represents all of the days in the array, and the index
represents its corresponding position in the array.days.forEach((day,index)=>{// loop body})
days
array, we will check if the day index is equal to the value returned by the getDay()
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)}
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! 😊