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 Loops, Arrays and Objects Tracking Multiple Items with Arrays Useful Array Methods

What is the difference between .concat() and .push()? Can we substitute the two?

I noticed that .concat() basically does the same thing that .push() does. Can we use the two synonymously or are there differences?

1 Answer

Hey,

Concat is used for joining two separate arrays into one array output - it doesn't affect the original arrays if they are already assigned to a var. e.g. var nums = [1,2,3]; var nums2 = [7,8,9]; console.log(nums.concat(nums2)); // this outputs [1,2,3,7,8,9] console.log(nums) // this still outputs [1,2,3] as the above didn't alter the original var

However, when using .push the above example nests the 'joining' array into the first var nums = [1,2,3]; var nums2 = [7,8,9]; console.log(nums.push(nums2)); // outputs [1,2,3,[7,8,9]] - notice the nested array console.log(nums) // outputs [1,2,3,[7,8,9]] as the above .push() has altered the original nums variable.

Hope that makes sense.

bestanswer. Thanks Rajith.