2018-09-30 23:01:58 +01:00
---
id: 587d7b89367417b2b2512b48
title: Use the Spread Operator to Evaluate Arrays In-Place
challengeType: 1
2019-08-05 09:17:33 -07:00
forumTopicId: 301222
2021-01-13 03:31:00 +01:00
dashedName: use-the-spread-operator-to-evaluate-arrays-in-place
2018-09-30 23:01:58 +01:00
---
2020-11-27 19:02:05 +01:00
# --description--
2018-09-30 23:01:58 +01:00
ES6 introduces the < dfn > spread operator< / dfn > , which allows us to expand arrays and other expressions in places where multiple parameters or elements are expected.
2020-11-27 19:02:05 +01:00
The ES5 code below uses `apply()` to compute the maximum value in an array:
2019-05-17 06:20:30 -07:00
```js
var arr = [6, 89, 3, 45];
var maximus = Math.max.apply(null, arr); // returns 89
```
2020-11-27 19:02:05 +01:00
We had to use `Math.max.apply(null, arr)` because `Math.max(arr)` returns `NaN` . `Math.max()` expects comma-separated arguments, but not an array. The spread operator makes this syntax much better to read and maintain.
2019-05-17 06:20:30 -07:00
```js
const arr = [6, 89, 3, 45];
const maximus = Math.max(...arr); // returns 89
```
2020-11-27 19:02:05 +01:00
`...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. The following code will not work:
2019-05-17 06:20:30 -07:00
```js
const spreaded = ...arr; // will throw a syntax error
```
2020-11-27 19:02:05 +01:00
# --instructions--
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
Copy all contents of `arr1` into another array `arr2` using the spread operator.
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
# --hints--
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
`arr2` should be correct copy of `arr1` .
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
```js
assert(arr2.every((v, i) => v === arr1[i]) & & arr2.length);
2018-09-30 23:01:58 +01:00
```
2020-11-27 19:02:05 +01:00
`...` spread operator should be used to duplicate `arr1` .
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
```js
assert(code.match(/Array\(\s*\.\.\.arr1\s*\)|\[\s*\.\.\.arr1\s*\]/));
```
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
`arr2` should remain unchanged when `arr1` is changed.
```js
assert((arr1, arr2) => {
arr1.push('JUN');
return arr2.length < arr1.length ;
});
```
# --seed--
## --seed-contents--
2018-09-30 23:01:58 +01:00
```js
const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY'];
let arr2;
2019-03-25 19:49:34 +05:30
2020-03-02 23:18:30 -08:00
arr2 = []; // Change this line
2019-03-25 19:49:34 +05:30
2018-09-30 23:01:58 +01:00
console.log(arr2);
```
2020-11-27 19:02:05 +01:00
# --solutions--
2018-09-30 23:01:58 +01:00
```js
2018-10-14 11:15:54 +05:30
const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY'];
let arr2;
2019-03-25 19:49:34 +05:30
arr2 = [...arr1];
2018-09-30 23:01:58 +01:00
```