DEV Community

Randy Rivera
Randy Rivera

Posted on

Using the Spread Operator to Evaluate Arrays In-Place

ES6 introduces the spread operator, which allows us to expand arrays and other expressions in places where multiple parameters or elements are expected.

  • Math.max() expects comma-separated arguments, but not an array. The spread operator makes this syntax much better to read and maintain.
const arr = [50, 10, 23, 234, 54];
const maxNum = Math.max(...arr);

 console.log(maxNum); will display 234
Enter fullscreen mode Exit fullscreen mode

...arr returns an unpacked array. In other words, it spreads the array. However, the spread operator only works in-place, like in an argument to a function or in an array literal.

const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY'];
let arr2;

arr2 = [...arr1];  
Enter fullscreen mode Exit fullscreen mode
console.log(arr2);
[ 'JAN', 'FEB', 'MAR', 'APR', 'MAY' ]
Enter fullscreen mode Exit fullscreen mode

Here we copied all contents of arr1 into another array arr2 using the spread operator.

Top comments (0)