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.

Justin Blalock
Justin Blalock
8,206 Points

bestanswer. Thanks Rajith.