Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Array Iteration Methods Combining Array Methods Nested Data and Additional Exploration

spread operator in this case

Hi,

can someone help me understand what the spread operator does in this case? [...arr, ...innerMovies]

thanks

Andrey Misikhin
Andrey Misikhin
16,529 Points

It is concatenation of two arrays. For example,

let arr = [1, 2, 3];
let innerMovies = ['a', 'b', 'c'];
let result = [...arr, ...innerMovies];
console.log(result);

If you will do it, than you will see, that you received a new array, that consists of previous two.

[1, 2, 3, 'a', 'b', 'c']

1 Answer

Steven Parker
Steven Parker
231,236 Points

What the spread operator itself does is to convert a collection of items into its individual elements. In your example, "arr" is an array with potentially several elements; and "...arr" is the elements all listed out as separate items.

This lets you do things in one step that would otherwise require loops, such as your example of re-combining multiple arrays into a single one.