Array.prototype.map() expects a return value from arrow function

The Array.prototype.map() method iterates over an array and creates a new array by executing a provided function on each element of the original array. The provided function (also known as the callback function) should have a return value.

Here is an example to demonstrate the usage of map():


const numbers = [1, 2, 3, 4, 5];

// Using map() to double each number in the array
const doubledNumbers = numbers.map((num) => {
  return num * 2;
});

console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]
  

In the above example, the map() method is used to create a new array doubledNumbers. The callback function takes each element of the numbers array and multiplies it by 2, returning the doubled value. The resulting array contains the values [2, 4, 6, 8, 10].

It is important to note that the callback function provided to map() should have a return statement. The value returned by the callback function will be added to the new array. If no return statement is present, the resulting array will contain undefined values.

Here is an example demonstrating the importance of having a return statement in the callback function:


const names = ['John', 'Jane', 'Mike'];

// Using map() to add 'Hello' prefix to each name
const greetings = names.map((name) => {
  console.log(`Hello, ${name}!`);
});

console.log(greetings); // Output: [undefined, undefined, undefined]
  

In the above example, the greetings array does not contain the expected values of ‘Hello John!’, ‘Hello Jane!’, and ‘Hello Mike!’. This is because the callback function in map() does not have a return statement. As a result, the new array contains undefined values.

To fix this, we need to modify the code to include a return statement in the callback function:


const names = ['John', 'Jane', 'Mike'];

// Using map() to add 'Hello' prefix to each name
const greetings = names.map((name) => {
  return `Hello, ${name}!`;
});

console.log(greetings); // Output: ['Hello, John!', 'Hello, Jane!', 'Hello, Mike!']
  

Now, the greetings array contains the desired values since the callback function has a return statement, returning the modified string for each element in the names array.

Read more

Leave a comment