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
2018-09-30 23:01:58 +01:00
---
## Description
< section id = 'description' >
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.
The ES5 code below uses < code > apply()< / code > 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
```
2018-09-30 23:01:58 +01:00
We had to use < code > Math.max.apply(null, arr)< / code > because < code > Math.max(arr)< / code > returns < code > NaN< / code > . < code > Math.max()< / code > 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
```
2018-09-30 23:01:58 +01:00
< code > ...arr< / code > returns an unpacked array. In other words, it < em > spreads< / em > 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
```
2018-09-30 23:01:58 +01:00
< / section >
## Instructions
< section id = 'instructions' >
Copy all contents of < code > arr1< / code > into another array < code > arr2< / code > using the spread operator.
< / section >
## Tests
< section id = 'tests' >
```yml
2018-10-04 14:37:37 +01:00
tests:
2019-03-25 19:49:34 +05:30
- text: < code > arr2</ code > should be correct copy of < code > arr1</ code > .
testString: assert(arr2.every((v, i) => v === arr1[i]));
2019-11-27 02:57:38 -08:00
- text: < code > ...</ code > spread operator should be used to duplicate < code > arr1</ code > .
2019-08-06 17:56:48 -04:00
testString: assert(code.match(/Array\(\s*\.\.\.arr1\s*\)|\[\s*\.\.\.arr1\s*\]/));
2019-03-25 19:49:34 +05:30
- text: < code > arr2</ code > should remain unchanged when < code > arr1</ code > is changed.
testString: assert((arr1, arr2) => {arr1.push('JUN'); return arr2.length < arr1.length } ) ;
2018-09-30 23:01:58 +01:00
```
< / section >
## Challenge Seed
< section id = 'challengeSeed' >
< div id = 'js-seed' >
```js
const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY'];
let arr2;
2019-03-25 19:49:34 +05:30
arr2 = []; // change this line
2018-09-30 23:01:58 +01:00
console.log(arr2);
```
< / div >
< / section >
## Solution
< section id = 'solution' >
```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
```
2019-07-18 08:24:12 -07:00
2018-09-30 23:01:58 +01:00
< / section >