Difference between these two functions that handle the state

35 Views Asked by At

I tried these two functions and I thought they do the same thing, but apparently no.

The first Function:

    setEatenFoodList(prevList => {
      const newList = [];
      for (let i=0 ; i<prevList.length ; i++) {
        if (i === index){
          const editedFood = prevList[i];
          editedFood.removingFade = true;
          newList.push(editedFood)
        } else {
          newList.push(prevList[i])
        }
      }
      return newList;
    })

The second Function:

    setEatenFoodList(prevList => {
      prevList[index].removingFade = true;
      return prevList;
    })

I don't see the difference ?

1

There are 1 best solutions below

3
On

The first code creates a new list called "newList" and iterates through the elements of the original list "prevList" and adds them to the new list. If the current index of the loop is equal to the variable "index", it creates a new variable called "editedFood" which is a copy of the element at that index, sets the "removingFade" property of "editedFood" to true and pushes it to the "newList". Finally, it returns the "newList" as the output.

The second code is simpler, it directly modifies the "prevList" by setting the "removingFade" property of the element at index "index" to true. And it returns the original list "prevList" as output.

The main difference between the two codes is that the first one creates a new list, whereas the second one modifies the original list.

More simply: the first function iterates through all the elements of newList and pushes everything inside the newList. The second function pushes everything into the original list (prevList)