1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

JS basics, destructuring of objects

Discussion in 'JavaScript' started by iago111, Apr 18, 2021.

  1. #1
    Hello I don't undersand the following destructuring assignment:

    
    
    const seasonConfig = {
      summer: {
        text: "Lets hit the beach",
        iconName: "sun",
      },
      winter: {
        text: "Burr, it is chilly",
        iconName: "snowflake",
      },
    };
    
    const getSeason = (lat, month) => {
      if (month > 2 && month < 9) {
        return lat > 0 ? "summer" : "winter";
      } else {
        return lat < 0 ? "winter" : "summer";
      }
    };
    
      const season = getSeason(37.23452, new Date().getMonth());
    
      const { text, iconName } = seasonConfig[season];
    
    Code (JavaScript):
    seasonConfig are nested objects, right. However, when I fetch the season (summer or winter), I put it into an array-like structure: seasonConfig[season]; for the destructuring assignment

    Why is this? Season config is obviously not an array!?

    Thanks a lot!!
     
    iago111, Apr 18, 2021 IP
  2. iago111

    iago111 Member

    Messages:
    99
    Likes Received:
    4
    Best Answers:
    1
    Trophy Points:
    33
    #2
    yes, it's because seasonConfig[season] is a associative array e.g. seasonConfig["summer"] and with that, it is an object
     
    iago111, Apr 20, 2021 IP
  3. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #3
    Technically this isn't destructuring, it's object assignment. When an object assignment has no name, the names inside it are used to index the target instead. This can be REALLY confusing given that if text and iconName were local variables, they'd be used instead of the values from the assignment. It's one of the reasons I hate this type of construct as depending on where you use it and what variables are and are not assigned, Christmas only knows how JS is going to handle said code.

    One of the many reasons JS is an ugly kludge, and I don't entirely grasp why people are in such a rush to use said shit-show server-side. We only ever used it client-side because it was all we had.
     
    deathshadow, May 27, 2021 IP