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 trialSamantha Weglinski
3,154 PointsWhat 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
Rajith Attale
Courses Plus Student 3,662 PointsHey,
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.
Justin Blalock
8,206 PointsJustin Blalock
8,206 Pointsbestanswer. Thanks Rajith.