map days to index in javascript

To map days to index in JavaScript, you can create an array and use the getDay() method of the Date object to get the day of the week, starting with Sunday as 0 and ending with Saturday as 6.

index.tsx
const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

const date = new Date();
const dayOfWeek = date.getDay();

console.log(`Today is ${days[dayOfWeek]}.`); //prints "Today is [day of the week]."
237 chars
7 lines

This code creates an array days that contains the days of the week in order. It then creates a Date object date representing today's date and uses the getDay() method to get the day of the week as an index. Finally, it uses this index to look up the corresponding day of the week in the days array and prints it to the console.

gistlibby LogSnag