Why doesn't map work for "never mutate state"?

Hi all,
I’m following the Front-End libraries curriculum and I’m on the Redux section called Never Mutate State

The Guide Entry for this challenge doesn’t mention using map as a solution.

According to w3schools the map method does not alter the original array and returns a new one.

so why is it that this solution will not work?

const immutableReducer = (state = todos, action) => {
  switch(action.type) {
    case ADD_TO_DO:
      // Don't mutate state here or the tests will fail
      return state.map(t => { return t; }).push(action.todo);
    default:
      return state;
  }
};

My mistake. I overlooked that the push method returns a number representing the new length after adding something to an array, not the array itself.

using a map approach in fact does work, provided it’s done like this:

const immutableReducer = (state = todos, action) => {
  switch(action.type) {
    case ADD_TO_DO:
      // Don't mutate state here or the tests will fail
      let newArray = state.map(t => { return t; });
      newArray.push(action.todo);
      return newArray;
    default:
      return state;
  }
};
2 Likes

This isn’t any point using map here – you’re literally just using it to copy an array. If you want a new array with the new element added, the JS provides the concat method for doing that:

    case ADD_TO_DO:
      return state.concat(action.todo);
2 Likes

I certainly didn’t mean to imply that using map is the best solution. It’s just one that came to mind when prompted by the challenge, and I was wondering why I couldn’t get it to work.

When I read the w3schools page for the concat method I got hung up on the part that says:

The concat() method is used to join two or more arrays.

It didn’t occur to me that it would work even if the argument passed to it was not an array.

1 Like