Use of spread operator


#1

I’ve been reading Redux documentation and I saw this piece of code, which returns state using spread operator. I don’t understand its use in this context. What exactly does it do? What does ...state mean (is)?

function todos(state = [], action) {
  switch (action.type) {
    case 'ADD_TODO':
      return [
        ...state,
        {
          text: action.text,
          completed: false
        }
      ]
    case 'COMPLETE_TODO':
      return [
        ...state.slice(0, action.index),
        Object.assign({}, state[action.index], {
          completed: true
        }),
        ...state.slice(action.index + 1)
      ]
    default:
      return state
  }
}

#2

...state is a copy of state, rather than a reference to it.

I’m unclear as to why ...state.slice(), though, since slice also creates a new array. Perhaps just for consistency (vs performance tradeoff).


#3

So, what’s the difference between returning ...state in case of ADD_TODOS and the default one when ‘just’ state is returned?


#4

In general, to prevent mutations of state from mutating the result of the function. In this specific case, I don’t know.


#5

Thanks for your help :grinning:!