Search code examples
javascriptjavascript-objectsdestructuring

Javascript destructuring in method


Can someone explain what exactly is going on in depth and if doing it this way is best practice for this line:

getAdvertisingChannelHtml({site, adViews, clicks, conversions, conversionRate} = this){

My understanding is that I am destructuring in a method and passing Object Properties in a method and making it equal to the this object?


class AdvertisingChannel {
  constructor(data) {
    Object.assign(this, data);
    this.conversionRate = (this.conversions / this.clicks) * 100;
  }
  getAdvertisingChannelHtml(
    { site, adViews, clicks, conversions, conversionRate } = this
  ) {
    return `
          <div class="site-name"> ${site} </div>
          <div>Views: ${adViews} </div>
          <div>Clicks: ${clicks} </div>
          <div>Conversions: ${conversions} </div>
          <div>Conv. Rate: <span class="highlight"> ${conversionRate} %</span></div> 
      `;
  }
}


Tried looking at documentation and trying to find out more about what exactly is going on but was still confused.


Solution

  • The function will destructure its Object parameter and assign the values to specific variables (site, adViews, clicks, conversions, conversionRate). The parameter also got set to this by default if you called the function without passing an argument.

    const data = {
      site: 'stackoverflow.com',
      adViews: 10,
      clicks: 1000,
      conversions: 10,
    };
    const advertisingChannel = new AdvertisingChannel(data);
    
    advertisingChannel.getAdvertisingChannelHtml();
    
    /**
     * site: 'stackoverflow.com'
     * adViews: 10
     * clicks: 1000
     * conversions: 10
     * conversionRate: 1
     */
    
    advertisingChannel.getAdvertisingChannelHtml({
      site: 'example.com',
      adViews: 2,
      clicks: 2000,
      conversions: 20,
    });
    
    /**
     * site: 'example.com'
     * adViews: 2
     * clicks: 2000
     * conversions: 20
     * conversionRate: undefined ( because it does not set yet)
     */
    
    
    

    Refer: Default parameters