If you're only appending a single variable, then push()works just fine. If we need to append another array, use concat():
Will spit out:
The concat does not affect ar1 and ar2 unless reassigned, for example:
Will display:
Solution 3:
WE think it's worth mentioning that push can be called with multiple arguments, which will be appended to the array in order. For example:
As a result of this we can use push.apply to append an array to another array like so:
Annotated ES5 has more info on exactly what push and apply do.
2016 update: with spread , we don't need that apply anymore, like:
Solution 4:
We can use push and apply function to append two arrays.
It will append array2 to array1. Now array1 contains [11, 32, 75, 99, 67, 34]. This code is much simpler than writing for loops to copy each and every items in the array.
Solution 5:
Use concat:
a now contains all the elements, [1, 2, 3, 3, 4, 5].