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 trialJoe Hilton
Courses Plus Student 4,893 PointsStuck with trying to unshift and shift at the same time
The challenge is to add 'firstWord' to the start of the 'spareWords' array but also use shift to remove it simultaneously and I just don't know how to do it
2 Answers
Dino Paškvan
Courses Plus Student 44,108 PointsYou are slightly misreading the challenge task:
On line 18, use a method on the 'spareWords' to set 'firstWord' to be first word of the 'spareWords' array whilst simultaneously removing it from the beginning of the array.
The .shift()
method removes the first item in the array it was called on, but it also returns a value — the element that was removed. That value can then be stored inside a variable:
var firstWord = spareWords.shift();
Kenneth Camilleri
7,816 PointsYou're looking for the splice()
function. Here's the syntax:
splice( <Index of selected element>, <number of elements to remove>, [<comma seperated list of elements you want to add>]
)
So for example, doing splice(1, 1, "Replace") will replace the array[1] with "Replace".
Joe Hilton
Courses Plus Student 4,893 PointsJoe Hilton
Courses Plus Student 4,893 PointsOhhhh right, now that makes sense. I though it was asking you to insert a word to the beginning of the array and remove it at the same time. Thank you very much for your help!!