2

I came across this function, called generateMessage which takes 2 parameters and returns and object. The function is as follows:

var generateMessage = (from, text)=>{
    return {
        from,
         text,
        createdAt: new Date().getTime()
    }
};

module.exports = {generateMessage};

This does NOT throw any errors, and attaches 3 properties to the returned object: '.from' , '.text' and '.createdAt', I am confused about the '.from' and '.text' properties.

My question is why don't we write from: from , text:text, in this way the returned object will have a proto property of .from and .text, which will have their values as the from and text from the parameters.

Why does just writing from and text for the returned object work in this case?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
pi2018
  • 347
  • 2
  • 11
  • 2
    you can write `from:from` and `text: text` - it's a stylistic choice. It's syntactic sugar, much like the fat arrow function (`=>`) – zfrisch Aug 15 '18 at 21:27
  • 2
    it is a short hand notation, if your variable is named from and the property is named form you can write `from` instead of `from: from` it will have the same effect – user9748360 Aug 15 '18 at 21:27

1 Answers1

5

That's ECMAScript's 'shorthand''s property and notation:

http://es6-features.org/#PropertyShorthand

http://es6-features.org/#ObjectMatchingShorthandNotation

It's as the name suggests, a shorthand method of object definition.

Mr.M
  • 100
  • 6