Hello everyone! I’d like to ask for a help in explaining to me code below?
Here’s the link to kata Training on Unlucky Days | Codewars

``````function unluckyDays(year){
let result = 0;
for (let month = 0; month < 12; month++) {
let d = new Date(year, month, 13);
if (d.getDay() == 5) {
result ++
}
}
console.log(result)
return result
}
``````

Generally I understood, how the code works. Let me go through the steps. So to make clear parts, which are unclear for me.

1. We need to find unlucky days
2. First in a code, variable result was created to count unlucky days. Also for the beginning it’s empty
3. Then we’ve to loop through months. That’s why it’s set to 12.
4. Then here I know how the object new Date works. I don’t understand, why do we need to put 13 in the end here: “let d = new Date(year, month, 13);”
Year will be taken from argument of the function, month will be taken from loop. But why do we need to add 13 there?
5. Then we are getting a date out of the above written code and comparing it to 5. This part also confuses me a lot. Why do we need to compare it with 5 I thought we need to compare it with 13.

I know that I didn’t understand most important part of the code. But I want to learn it and be able to use it in the future. Thanks a lot for your time and help!

We are looking to find out how many Friday the 13ths there are in a year.

The year is passed in and the month comes from the loop. This:

``````d = new Date(year, month, 13);
``````

Will get the date object for the 13th day of that month and year. That is one of the ways to create a date object. When in doubt, check the docs.

So, we have a date object for the 13th day of that month. Now we see what day of the week that is. In a 0 indexed week that starts on Sunday, the number for Friday is 5. So this line:

``````if (d.getDay() == 5) {
``````

is asking “is the that day (the 13th of that month) a Friday?”

If it is true, we increment our counter.

1 Like

Thanks a lot for your time and help! Now everything is clear to me. I’m very new in programming and JS. Trying to switch my career to Frontend Web Developer. Currently learning JS. Thanks again!!!

1 Like

We’ve all been there, pay it forward.

3 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.