Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
210,867 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.