• aebletrae [she/her]@hexbear.net
    link
    fedilink
    English
    arrow-up
    0
    ·
    1 year ago

    You want to create the date “31st February”, but it’s JavaScript that’s cursed?

    Write a less side-effecty function.

    function getMonthName(monthNumber) {
        const date = new Date(2023, monthNumber - 1, 1);
        return date.toLocaleString([], { month: 'long' });
    }
    
    • ☆ Yσɠƚԋσʂ ☆@lemmy.mlOP
      link
      fedilink
      arrow-up
      1
      ·
      edit-2
      1 year ago

      The point is that this scenario exists in Js in the first place. It’s a completely unnecessary rake left around for people to step on. Also, the function isn’t side effecty since it doesn’t make implicit references outside its scope. The fact that the date is mutable is an internal concern there. You could just as easily do

      function getMonthName(monthNumber) {
        const date = new Date();
        date.setDate(1);  
        date.setMonth(monthNumber - 1);
      
        return date.toLocaleString([], { month: 'long' });
      }
      

      The problem here isn’t with side effects, but with having to know that you want to set your date to first day to get the next month reliably.