JavaScript, Web Development

TIL – JavaScript append an array to an array

TIL – JavaScript append an array to an array

I was today’s years old when I learn that you can actually append an array to an array using the push method instead of the concat method. concat is nice but it creates a new array but what I wanted is to simply modify the original array, therefore, avoid allocating more memory.

JavaScript’s array.push actually accepts multiple parameters so we can just use the spread operator to merge two arrays.

const names = ['foo', 'bar'];
const otherNames = ['alpaca', 'llama', 'dog', 'cat'];

Why avoid allocation memory?

It’s easy to create new memory in JavaScript and it becomes my habit given my React.js experience. However, in the context of a loop or even recursion, we should strive to use memory efficiently.

Featured image by Andrea Piacquadio.

Leave a reply

Your email address will not be published. Required fields are marked *