The innermost if checks if adding one day to the 30th results in the same month. If it does, the month has 31 days. If not, it has 30 days.

The middle if checks if adding one day to the 29th keeps it in the same month. If it does, it continues to the innermost if. If not, it directly returns 29.

The outermost if starts with the 28th, and if adding one day keeps it in the same month, it proceeds to the middle if. If not, it directly returns 28.

It’s interesting seeing all the workarounds we have to come up with when we need something there isn’t a straightforward method to get it.

Here’s also another way to approach this:
Given the month and year, string together a date for the first day of that month and use parseDate() on that.
For this month, 10, and this year, 2023, we get 10-1-2023.
Then, add a month, so 11-1-2023.
Then, remove 1 day, so 10-31-2023.
Use a formatDate if you just need to get the day number.