Skip to content Skip to sidebar Skip to footer

Why Doesn't Array#map Return The Correct Array?

When I write something like this: var x = [1,2,3].map(x => { a : 'hello' }); I expect to receive something like [{a:'hello'},{a:'hello'},{a:'hello'}], but instead it returns a

Solution 1:

The "object" is treated as a block because arrow functions have multiple acceptable syntaxes. They includes a block which houses multiple statements:

param1 => { statements }
(param1, param2, …, paramN) => { statements }

In actuality your current code is interpreted as a block with a label and a string expression, not an object literal. Thus, your callback doesn't return anything and your array becomes an array of undefineds.

Wrap it in parentheses so that it is an expression and interpreted as an object literal (because blocks are not expressions, they are statements, and code inside grouping must be an expression):

var x = [1,2,3].map(x => ({ a : 'hello' }));

Solution 2:

You need some parenthesis around the object, otherwise you get a block statement with a label.

To prevent the block statement in arrow functions, you need to use the grouping operator to get an expression as return value.

var x = [1, 2, 3].map(x => ({ a: 'hello' }));

console.log(x);

Solution 3:

You need to put the returned object in parentheses:

var x = [1,2,3].map(x => ({ a : 'hello' }));

Otherwise, the code in curly braces it is treated as a body of a function.

Solution 4:

var x = [1,2,3].map(x => ({ a : 'hello' }));

Post a Comment for "Why Doesn't Array#map Return The Correct Array?"