2

What’s a practical use case of the ES6 spread operator? I’m pretty fresh and would just like to see a real world example where you would need to destructure some array values and apply them to function Params.

Comments
  • 1
    @theScientist I reference MDN quite a bit. That didn’t really answer my question. And I’m sure I could google some practical examples showing situations where ‘spread’ was the answer. But I thought I would start a conversation with the devRant community instead.
  • 1
    So let's say a function you are trying to call uses the a rest parameter, and you are wrapping it in another function, if the wrapping functions takes an array or rest param, you would use the spread operator to prevent the array from becoming nested in the wrapped function.

    function wrap(...abc) {
    return inner(...abc)
    }

    If you didn't add the spread on the parameter that was passed the inner function would see the abc param value as a 2 dimensional array with the real param array stored in the first element instead of the intended 1d array.
  • 0
    Basically expanding on my previous answer, it takes an array and maps it to rest parameters, so if your wrapper function takes a array as a parameter instead of rest it would still let the inner rest function be called.
Add Comment