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

  • How to get all values out of array and its sub-arrays
  • Fill 2D array in alternate squares
  • What is a safe length of JavaScript strings?
  • Get key of associative array
  • Turning objects into an array of counts
  • Add values of matching keys in array of objects
  • and

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

  • How to serialize a JavaScript associative array?
  • Array in a loop
  • ng-if check if array is empty
  • How do I check if an array includes an object in JavaScript?
  • flatten object inside array
  • Keep getting undefined when calling 2 dimensional array in JS
  • 3 Solutions collect form web for “Array map returning array of undefined when should return array of objects”


    • 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 })));

    You need to wrap object in ()

    var result = ['a', 'b', 'c'].map((x) => ({ letter: x }))

    A function that lacks an explicit return statement will return undefined.
    () => {} is equivalent to function(){}.
    x => x is equivalent to function(x){ return x;}

    So arrow function without {} will return computed value of the expression.