skip to Main Content

I like how this map works but I have a suspition that it might be bad practice to use return on every iteration of a loop

Is this a bad practice?

Thank you

const array = [
  ["Header 1", "Header 2"],
  [1, 2],
  [3, 4],
];

const mappedArray = array.map((row, index) => {
  if (index === 0) {
    return row;
  } else {
    return row.map((value) => value * 2);
  }
});

I have tryed searching for an awnser to this but found nothing

2

Answers


  1. This is fine, the way the array.map function works is by calling your function to see how to the map the values.

    The main concern would be if you’re calling the variable often, if not I wouldn’t worry about it

    Login or Signup to reply.
  2. You actually need to return on every iteration of the Array.map method. There’s a ‘sort of’ equivalent Array.forEach method that works exactly the same, except it doesn’t automatically return an array. If you don’t think you need to return an array, but instead you want to do something with each item in the array, the forEach method will save a little bit of memory, but if you actually have a use case that needs the map function over the forEach function, returning is required. The app won’t break if you don’t, but you’ll be assigning variables or storing things in memory that you’re not actually using.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search