DEV Community

Randy Rivera
Randy Rivera

Posted on

Combining Arrays with the Spread Operator

  • Another huge advantage of the spread operator is the ability to combine arrays, or to insert all the elements of one array into another, at any index. Spread syntax makes the following operation extremely simple.
  • Let's take this for example. I have defined a function spreadOut that returns the variable sentence. I modified the function using the spread operator so that it returns the array ['learning', 'to', 'code', 'is', 'fun'].
function spreadOut() {
  let fragment = ['to', 'code'];
  let sentence = ['learning', ...fragment, 'is', 'fun']; <----
  return sentence;
}

console.log(spreadOut()); will display  
['learning', 'to', 'code', 'is', 'fun']
Enter fullscreen mode Exit fullscreen mode

Latest comments (0)