Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
getday()
communitycreator

How to get day of the week in JavaScript using getDay()

Theodore Kelechukwu Onyejiaku

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

  1. First, we create an array of the days of the week:
let days = ["Sunday", "Monday", "Tuesday", "Wednesday","Thursday", "Friday","Saturday"]
  1. The array above will be looped using the 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
})
  1. Finally, as we loop the 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)
}

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! 😊

RELATED TAGS

javascript
getday()
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring