1

Consider a scenario where in you are trying to iterate over a const array. Would there be any difference between

[...arr].forEach((elem) => {
  // your operations
});

and

 arr.forEach((elem) => {
   // your operations
 });

Can these two be used interchangeably?

simeg
  • 1,889
  • 2
  • 26
  • 34
  • 3
    Yes, they can. I don't see why you would want to use the first expression rather than the second one. – Blackhole Jul 23 '18 at 14:19
  • Yes!! a constant array will only have the address as constant, you can still change/add elements to it. But when you use the spread operator, you don't touch the original array – Ashish Ranjan Jul 23 '18 at 14:19

1 Answers1

4
  1. It will make a copy of the array. If the callback function would use the array parameter and it would modify it, that would make a difference. E.g.:

    [...arr].forEach((val, i, a) => a.push(val))
    
  2. If arr is not an array but an array-like, it will turn it into an array and thereby allow you to forEach over it. E.g.:

    [...document.getElementsByTagName('p')].forEach(p => console.log(p))
    
deceze
  • 510,633
  • 85
  • 743
  • 889