0

I can't quite understand the differences between [...array].map(...) and [...array.map(...)]. Are they any different? If yes, why and how?

2
  • 2
    Have you tried these 2? What differences did you notice? Commented Nov 29, 2021 at 18:49
  • Or just array.map(...) which does the same thing. Commented Nov 29, 2021 at 18:54

2 Answers 2

4
  • [...array].map(...) will generate a new shallow copy of an array ([...array]) and then .map over it and return a brand new array as the return value.
  • [...array.map(...)] will .map over the original array, which will return a new array, and then immediately make a shallow copy of the new array ([...array.map(...)]). I must admit, I don't really understand the use case for this approach-- because .map itself is returning a brand new array that no other variable should be holding a reference to, I don't see any value in immediately casting a shallow copy of it.

(Also, as pointed out by chazsolo in the comments, if array were not an array, but in fact some other type like a Set, the [...array.map(...)] approach would actually throw an error, as Set instances have no .map method).

Sign up to request clarification or add additional context in comments.

2 Comments

I'd mention that array could be an Iterable, like a Set. The first case would work as expected, the second would throw a TypeError.
@chazsolo -- good call out-- updated, thanks!
3

Well [...array.map(...)] is the same as array.map(...) except that it does an extra unnecessary spread/copy after the mapping is done.

The [...array].map(...) has an small difference, due to the 3rd parameter passed in map (the array it self).

And as mentioned in another comment, by @chazsolo, this case will handle cases where the array variable is not an array, so it does not have the map method, but can be iterated and the spread will create an array out of it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.