DEV Community

loading...

Combining Arrays with the Spread Operator

rthefounding profile image Randy Rivera ・1 min read
  • 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

Discussion (0)

Forem Open with the Forem app