4

I'm relatively new to ES6 Syntax. I had written a piece of code like follows:

const makeRange = (startTime, endTime) => {
    return { startTime: startTime, endTime: endTime };
};

This worked fine, though I thought I shouldn't need the function braces ({ ...body ...}) for a one line return. The Following code:

const makeRange = (st, et) => { startTime: st, endTime: et };

As pointed by IntelliJ or Webstorm: "Expression Statement is not assignment or call".

How should I do it correctly(if it is valid)?

  • 3
    The `{` after the `=>` is interpreted as the beginning of a code-block, not the beginning of an object literal, use `(st, et) => ({ startTime: st, endTime: et });` for objects – Nick Parsons Dec 31 '19 at 04:11
  • Thanks! [When to use `return` in es6](https://stackoverflow.com/questions/28889450/when-should-i-use-return-in-es6-arrow-functions) was helpful too as marked. – Prashant Vishwakarma Dec 31 '19 at 04:19

1 Answers1

9

You can use () to wrap it like this:

const makeRange = (st, et) => ({ startTime: st, endTime: et });

console.log(makeRange(1, 2));
Tân
  • 1
  • 15
  • 56
  • 102