Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array map returning array of undefined when should return array of objects

Why does

['a', 'b', 'c'].map((x) => { letter: x }) returns a array of undefined

and

['a', 'b', 'c'].map((x) => [{ letter: x }][0]) returns a array of objects correctly?

like image 811
Lucas Ferronato Avatar asked Dec 02 '25 17:12

Lucas Ferronato


1 Answers

Because

  • You use the curly brackets as block statement.

  • You have letter as a label.

  • x is just a value without some action.

  • The return of undefined is the standard return value of a function without any return statement with value.

    To return a value other than the default, a function must have a return statement that specifies the value to return. A function without a return statement will return a default value. In the case of a constructor called with the new keyword, the default value is the value of its this parameter. For all other functions, the default return value is undefined.

Correct call for mapping objects.

console.log(['a', 'b', 'c'].map(x => ({ letter: x })));
like image 155
Nina Scholz Avatar answered Dec 04 '25 08:12

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!