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

Computer Science Algorithms: Sorting and Searching Sorting Algorithms Code for Selection Sort

Andrew Whatmore
seal-mask
.a{fill-rule:evenodd;}techdegree
Andrew Whatmore
Full Stack JavaScript Techdegree Student 13,175 Points

[0] in JavaScript splice method

What is the [0] doing in the following line in the JavaScript version of the code? The code still seems to work without it. Thanks

sortedList.push(list.splice(indexToMove, 1)[0]);

1 Answer

Laura Coronel
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Laura Coronel
Treehouse Teacher

Great question Andrew Whatmore! 😊 The [0] accesses the first (and only) item in the array returned by splice().

The splice() method returns an array of the items it removes from the original array. Since you're removing just one item, [0] gets that item itself rather than the array containing it.

Without [0], you'd be pushing an array into sortedList instead of the individual item. The code might still run, but the resulting array would have a different structure.