Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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


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.