javascriptjsobject

Javascript object syntax that I can't recognize


I have this code snipet:

proxy('http://my-custom-api-endpoint.com', {
  proxyReqOptDecorator(options) {
    options.headers['x-forwarded-host'] = 'localhost:3000'
    return options
  }
})

It is a call to a function named proxy, the first argument is a string, but the second argument has a syntax than I can't recognize:

{
  functionName(args) {
    // statements
  }
}

Can someone explain that syntax please?


Solution

  • Its a shorthand method in Object Initializer to create a property whose value is a function.

    // Shorthand method names (ES2015)
    let o = {
      property(parameters) {}
    }
    
    //Before
    let o = {
      property: function(parameters) {}
    }
    

    This syntax is also sued in classes to declare class methods.

    class Animal { 
      speak() {
        return this;
      }
      static eat() {
        return this;
      }
    }class Animal { 
      speak() {
        return this;
      }
      eat() {
        return this;
      }
    }