Explain Codes LogoExplain Codes Logo

How to append something to an array?

javascript
array-methods
spread-operator
performance-tips
Anton ShumikhinbyAnton Shumikhin·Sep 2, 2024
TLDR

Append single item to an array using .push():

let arr = ['a', 'b']; arr.push('c'); // arr: ['a', 'b', 'c'], here 'c' joins the party!

Append multiple items with one shot to .push():

arr.push('d', 'e'); // arr: ['a', 'b', 'c', 'd', 'e'], now 'd' and 'e' couldn't resist either

Combine arrays using .concat():

let arr1 = ['a','b']; let arr2 = ['c','d']; let combined = arr1.concat(arr2); // combined: ['a', 'b', 'c', 'd'], arr1 stays as it was, no party crashers

Append methods

Merge arrays using the spread operator:

let mergedArray = [...arr1, ...arr2]; // mergedArray: ['a', 'b', 'c', 'd'], everyone's invited, yet original guest lists unchanged!

To append without mutating the original array:

let newArr = [...arr, 'newElement']; // newArr: ['a', 'b', 'c', 'newElement'], 'newElement' gets its own party!

Prepend to the array using unshift:

arr.unshift('start'); // arr: ['start', 'a', 'b', 'c'], 'start' jumps right at the front of the line!

Prepend multiple items with one go:

arr.unshift('zero', 'one'); // arr: ['zero', 'one', 'start', 'a', 'b', 'c'], 'zero' and 'one' decided to lead the way!

Working with large arrays

For large arrays, consider using apply with .push():

arr.push.apply(arr, anotherLargeArray); // Efficiently welcoming the entire guest list from anotherLargeArray to arr party!

Performance tips

In the realm of performance, .push() is efficient, yet for small arrays or specific scenarios direct assignment arr[arr.length] = newItem could be faster. Always balance speed and clarity.

arr[arr.length] = 'newElement'; // 'newElement' sneakily getting in

For large arrays, if you're hitting call stack limitations, chunk your input and append in parts.

Tailoring for use-cases

Tune the appending strategies for your specific scenario. Understand the nuances of each method to achieve superior performance and readability.

Unleashing ES6 power

Embrace the ES6 spread wizardry with .push():

arr.push(...['newItem1', 'newItem2']); // 'newItem1' and 'newItem2' just teleported in!

Remember:

  • .push() to append.
  • .unshift() for prepend.

Pitfalls & Traps

Keep an eye out for original array mutation with .push() and .unshift(). Always consider whether the modifications are intended or if you should birth a new array.