Get the Date of the Next Friday using JavaScript

Borislav Hadzhiev

Last updated: Jan 18, 2022

Photo from Unsplash

**To get the date of the next Friday:**

- Get the day of the month of the next Friday.
- Pass the result to the
`setDate()`

method. - The
`setDate`

method changes the day of the month for the given date.

index.js

`function getNextFriday(date = new Date()) { const dateCopy = new Date(date.getTime()); const nextFriday = new Date( dateCopy.setDate( dateCopy.getDate() + ((7 - dateCopy.getDay() + 5) % 7 || 7), ), ); return nextFriday; } // 👇️ Get Friday of Next Week console.log(getNextFriday(new Date())); // 👉️ Fri Jan 21 2022 // 👇️ Get Next Friday for specific Date console.log(getNextFriday(new Date('2022-01-25'))); // 👉️ Fri Jan 28 2022`

We created a reusable function that takes a `Date`

object as a parameter and
returns the next Friday.

If no parameter is provided, the function returns the next Friday of the current date.

The
setDate
method allows us to change the day of the month of a specific `Date`

instance.

The method takes an integer that represents the day of the month.

**To get the next Friday, we:**

Add

`5`

to the day of the week, e.g. Tuesday =`7 - 2 (Tuesday) + 5 = 10`

. Note that the getDay() method returns the day of the week where Sunday is 0, Monday is 1, Tuesday is 2, etc.Use the modulo operator to get the remainder of dividing

`10 % 7 = 3`

If the remainder is equal to

`0`

, then the current date is Friday and we have to default it to`7`

to get the date of the next Friday.The

`getDate()`

method returns the day of the month, e.g.`18 + 3 = 21`

, where`21`

is the day of the month for the next Friday.

**If the Date object stores a Friday:**

- Get the day of the month, e.g.
`21`

. - Calculate
`7 - day of the week (Friday = 5) + 5 = 7`

- Get the remainder -
`7 % 7 = 0 || 7 = 7`

. - Get the day of the month for the next Friday -
`21 + 7 = 28`

, where`28`

is the day of the month for the next Friday.

We created the `dateCopy`

variable in the function because the `setDate`

method
mutates the `Date`

instance in place.

If you use the same `Date`

object elsewhere in your code, this might lead to
confusing bugs.