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 Foundations Arrays Methods: Part 1

Abubakar Usman
Abubakar Usman
6,463 Points

Stuck in code challenge

I got an error message with this code

var lastWord = spareWords[spareWords.length];

// this is to add 'lastWord' to the end of the array 'spareWords'.

spareWords.pop();

// This is to remove 'lastWord' from the end of the array.

What have I got wrong?

to add a value to the end of an array you do:

arrayname.push(value);

so if you want to add lastWord to the end of the array spareWords your code should look something like this

spareWords.push(lastWord);

also I see what you did there to get the end of spareWords array, but I believe what they were looking for was

var lastWord = spareWords.pop();

which takes the last value from spareWords and stores it in the variable lastWord, which you then pass as a parameter to your push method

I hope this makes sense and I didnt confuse you further

one last thing, you are using a pop method to get the last value of sparewords and then using a push method to put it right back? I believe the challenge asks you to take the lastword and put it at the end of the saying array so:

saying.push(lastWord);

4 Answers

Michalis nailed this in the comments. Ask him to copy it as an answer and you can choose it as Best Answer ;-)

thomas bethell
thomas bethell
7,772 Points

Michalis,

Can you post what you did here? I am stuck on part 3 of 4.

ok gimme a minute to take a look

ok if you havent figured it out already here goes, part 3 asks you to add the contents of the firstWord variable back into the beginning of spacewords array

to add something to the beginning of an array we use the unshift() method on that array, and we pass the value we want to add in the parentheses, so we need to do this

saying.unshift(firstWord);

this says to the javascript interpreter to take the array saying and add firstWord to the beginning of it, and since firstWord is a variable, it will add the vallue of that variable to the begining of the array, which in this case is the word 'The'

I hope I helped