Home > Software engineering >  JS return structure
JS return structure

Time:10-27

What is the difference between {} and ( ) in JavaScript's return statement?

const fruits = [
  {
    name: "FaceBook",
    nickname: "FB",
  },
  {
    name: "Youtube",
    nickname: "YT",
  },
  {
    name: "AmazonWebService",
    nickname: "AWS",
  },
];
const count = fruits.reduce((acc, cur) => {
  return { ...acc, [cur.nickname]: cur.name };  // What does {} of return mean here?
}, {});

CodePudding user response:

If you are using {}, it will return it as an object, so you need to add a key into it.

See this example below for more explanations:

function test1() {
  return 'ok'
}

function test2() {
  return ('ok')
}

function test3() {
  return { message: 'ok' } // it won't accept: return {'ok'}
}

console.log(test1())
console.log(test2())
console.log(test3())
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

In your case, the [cur.nickname] is the key. And the cur.name is the value

CodePudding user response:

Since return is not a function, but a statement, It is syntactically similar to other simple control flow statements like break and continue that don't use parentheses either.

So parentheses in return are just like parentheses anywhere else, its for order of calculations or just grouping.

But when you use curly brackets in return its for returning a new object, that's also applicable anywhere else.

In conclusion they have nothing to do with the return statement.

CodePudding user response:

{} is a literal object initializer used to construct a new initialized object.

() is simple grouping of an expression. return ( ...acc, [cur.nickname]: cur.name ) would return the last expression cur.name as the comma operator evaluates left to right and return the last expression.

CodePudding user response:

return { ...acc, [cur.nickname]: cur.name }; will return a new Object

  • Related