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 3

Mark Tichenor
Mark Tichenor
1,986 Points

JavaScript foundations, Array's, stage 4. How do I do the first challenge task? concat + push?

I can concatenate the two arrays by using var saying = first.concat(second), but can't figure out how to add the word "dog" in on the same line.

3 Answers

Ken Alger
STAFF
Ken Alger
Treehouse Teacher

Mark;

Task 1 of this challenge asks:

On line 18, set the variable 'saying' to the concatenation of the 'first' and 'second' arrays with the word "dog".

The code for the script portion of the challenge is:

    <script>
      var first =  ["The", "quick", "brown", "fox", "jumps"]
      var second =  ["over", "the", "lazy"];
      var saying = first; 
      var shortSaying = saying;
      var sayingString = saying;
    </script>

Line 18 is the var saying = first; line.

In order to meet the challenge objectives we would concatenate the first and second arrays. Looking in the JavaScript documentation, there is the concat() method which concatenates arrays. Sounds like what we need.

It allows us to add additional items to the new array as well, such as dog.

So, to combine all of our tools we would use the syntax:

var saying = first.concat(second,"dog"); 

I hope it helps, and happy coding.

Ken

Mark Tichenor
Mark Tichenor
1,986 Points

So we use "dog" as a parameter in the method. Thanks Ken :)

Ken Alger
STAFF
Ken Alger
Treehouse Teacher

Mark,

Yes, that adds the value, in this case the string dog to the new array saying after the concatenation.

You could also do something like:

var saying = first.concat(second);
saying.push("dog");

I have forgotten if the push() method has been covered in the JavaScript Foundations course at this point yet, but it will add an item to the end of an array. That would create the same saying array, but it is obviously quicker to do it using the method in the previous post.

Ken