Search code examples
javascriptdry

Is there any way to shortcut repetitive functions in JS?


I am currently experimenting with JS and I made this code, the purpose of which is pretty self-explainatory:

const DAYS_IN_JULY = 31;
const DAYS_IN_APRIL = 30;
const DAYS_IN_FEBUARY = 28;
console.log('Days in July:', DAYS_IN_JULY);
console.log('Hours in July:', DAYS_IN_JULY * 24);
console.log('Minutes in July:', DAYS_IN_JULY * 24 * 60);
console.log('Seconds in July:', DAYS_IN_JULY * 24 * 60 * 60);
console.log('Days in April:', DAYS_IN_APRIL);
console.log('Hours in April:', DAYS_IN_APRIL * 24);
console.log('Minutes in April:', DAYS_IN_APRIL * 24 * 60);
console.log('Seconds in April:', DAYS_IN_APRIL * 24 * 60 * 60);
console.log('Days in Febuary:', DAYS_IN_FEBUARY);
console.log('Hours in Febuary:', DAYS_IN_FEBUARY * 24);
console.log('Minutes in Febuary:', DAYS_IN_FEBUARY * 24 * 60);
console.log('Seconds in Febuary:', DAYS_IN_FEBUARY * 24 * 60 * 60);

Is there any way to shorten the amount of lines here?

I tried to do something with arrays and for() loop, but it didn't work.


Solution

  • Yes, you can use arrays and loops to shorten your code. Here is an example:

    const months = [
      { name: 'July', days: 31 },
      { name: 'April', days: 30 },
      { name: 'February', days: 28 }
    ];
    
    for (const month of months) {
      console.log(`Days in ${month.name}:`, month.days);
      console.log(`Hours in ${month.name}:`, month.days * 24);
      console.log(`Minutes in ${month.name}:`, month.days * 24 * 60);
      console.log(`Seconds in ${month.name}:`, month.days * 24 * 60 * 60);
    }
    

    In this code, we define an array of objects, where each object represents a month with its name and number of days. We then use a for-of loop to iterate over each month object in the array and output the desired information for each month. The string template literal notation ${month.name} is used to insert the name of each month into the output.