0

I'm new to JavaScript, and after reading "JavaScript The Good Parts" I wanted to code something for fun. I stubled upon this code snipped that I can't understand:

const actions = {
  say(sessionId, context, message, cb) {
    console.log(message);
    cb();
  },
  merge(sessionId, context, entities, message, cb) {
    // Retrieve the location entity and store it into a context field
    const loc = firstEntityValue(entities, 'location');
    if (loc) {
      context.loc = loc;
    }
    cb(context);
  },
  error(sessionId, context, error) {
    console.log(error.message);
  },
  ['fetch-weather'](sessionId, context, cb) {
    // Here should go the api call, e.g.:
    // context.forecast = apiCall(context.loc)
    context.forecast = 'sunny';
    cb(context);
  },
};

It is a snipped from the wit.ai node.js client. In my understanding "actions" is an object, and "say", "merge", "error", and "['fetch-weather']" are functions saved as values without key.

How is it possible to define a function without the reserved word "function"?

I also can't comprehend the "['fetch-weather']"-part.

Dexygen
  • 12,287
  • 13
  • 80
  • 147
G. Kasev
  • 1
  • 1

3 Answers3

0

This is a new feature, shorthand method names, in ES6. It is the same as

const a = {
    say: function say(sessionId, context, message, cb) {
        console.log(message);
        cb();
    }
}
baao
  • 71,625
  • 17
  • 143
  • 203
0

I also can't comprehend the "['fetch-weather']"-part.

I suppose it was done because they use a - in the function-name.

So actions.fetch-weather(..); is illegal because the - is an operator.

On the other hand, with the actions['name']-notation, you can use any name.

dabyte
  • 1
  • 2
  • Thanks, I understad that you should use quotation marks when using "-" in a name, but why use the brackets? – G. Kasev Apr 22 '16 at 10:16
  • "Why use the brackets?" --> In order to use otherwise illegal names... and also to use computed names, for example you can easy write a new script language using this functionality. And sorry for that my comment was not clear enough for you, @FrancescoPezzella explained it more clear. – dabyte Apr 22 '16 at 11:41
0

How is it possible to define a function without the reserved word "function"?

You can find the answer here

I also can't comprehend the "['fetch-weather']"-part.

That kind of syntax has been introduced by ES6 with a feature called Computed Property Names, in which you can define property names dynamically.

With ES5 you cannot declare an invalid identifier like fetch-weather as property directly in an object literal.

ES6:

const actions = {
    ...,
    ['fetch-weather'](sessionId, context, cb) {
    },
    ...
};

ES5:

var actions = {
    // props here
};

actions['fetch-weather'] = function(sessionId, context, cb) {
    ...
};
Francesco Pezzella
  • 1,755
  • 2
  • 15
  • 18