1

Its known that someone can make a one-line array function like this to return the single value:

var func = (x) => x + 1 //func(2) == 3

and you can also make multi-line array-functions, whose values need to be manually returned:

var funcMultiline = (x) => {
   var result = 1;
   result += x;
   return result;
}

funcMultiline(4) == 5; //true

So the question: let's say I want to return a new object in one line, if I use the brackets, then the array-function is treated like a multi-line function, and doesn't actually return the object-literal. Is there any direct way to create an object literal in, lets say, a map function? Like:

[...Array(25)].map(e => {x: 5, y:10}) //this is a syntax error, but how can I make this work
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • 2
    You need to add brackets: `[...Array(25)].map(e => ({x: 5, y:10}))` – Amir Popovich Mar 05 '19 at 06:02
  • For the record, these are not "array functions". They are called "arrow functions" in JS and sometimes "lambda functions" (usually by people coming outside JS). – VLAZ Mar 05 '19 at 06:03

1 Answers1

4

Returning object literals using the concise body syntax params => {object:literal} will not work as expected.

You have to wrap the object literal with parenthesis:

var res = [...Array(25)].map(e => ({x: 5, y:10}))

console.log(res);
Mamun
  • 66,969
  • 9
  • 47
  • 59