Gotchas of Array.map method in JavaScript

Array.map method helps to iterate over the array elements. It also helps to manipulate the elements by iterating over it once in correct order.

But Array.map will only work on prefilled array. It won't iterate over empty arrays. For example,

// This will work
const authors = ['Param', 'Joshua'];
authors.map(author => {
  console.log('authors array ->', author);
  return author;
});

// This won't work
const emptyAuthors = new Array(6);
emptyAuthors.map(author => {
  console.log('empty array ->', author); // This will never get consoled
  return author;
});

console.log(emptyAuthors); // [undefined, undefined, undefined, undefined, undefined, undefined]

Then, what is the based way to create empty array that is iterable. You can use Array.fill to populate it,

// Prefill using `Array.fill`
const prefilledAuthors = new Array(3).fill(null);
prefilledAuthors.map((author, index) => {
  console.log('prefilled author index ->', index); // This gets consoled
  return author;
});

You can play with the code here,