Explain Codes LogoExplain Codes Logo

Add new value to an existing array in JavaScript

javascript
array-manipulation
best-practices
javascript-8
Anton ShumikhinbyAnton Shumikhin·Jan 28, 2025
TLDR

For a quick append to an array, go with push():

let arr = ['a', 'b']; arr.push('c'); // arr is now ['a', 'b', 'c']. No surprise here, right?

Expanding the array from the start? Not an issue with unshift():

arr.unshift('z'); // Check back at the start, it's now ['z', 'a', 'b', 'c']

Append Sanely

When you want to deal with array size, avoid new Array(). Stick to []:

let arr = []; // Short, simple and sweet arr.push('new value'); // arr just gained a new friend ['new value']

Dealing with new Array()

Start your arrays with []. It avoids surprises:

let arr = [3]; // Clearly an array with one element, 3. No magic. let confusingArr = new Array(3); // Did you want an array with three empty slots? Didn't think so.

Array-like objects? No problem.

Use Array.prototype.push.call() when wrestling array-like objects:

function addToObjectArray() { Array.prototype.push.call(arguments, 'new value'); // "This is Sparta!!!" ...just kidding. But we did kick 'new value' into the 'arguments' pit. return arguments; }

Handling multiple values

Got multiple new elements? push() has got you covered:

arr.push('d', 'e', 'f'); // arr is now ['z', 'a', 'b', 'c', 'd', 'e', 'f'] // What's a party without friends? More the merrier (up to about ~1.5 million items, but who's counting?)

Inserting at a specific index

Use Jedi mind control (aka Array.splice()) for exact insertions at any index:

arr.splice(2, 0, 'x', 'y'); // arr is now ['z', 'a', 'x', 'y', 'b', 'c', 'd', 'e', 'f'] // 'x' & 'y' just happened to cut in line... all cool with JavaScript!

Best Practices for Array Manipulation

Here are proven strategies to handle arrays the smart way:

Spread syntax

To make your array operation look fancier, employ the spread syntax (...):

let newArr = ['g', ...arr, 'h']; // newArr just asked arr's part over for a fancy dinner ['g', 'z', 'a', 'x', 'y', 'b', 'c', 'd', 'e', 'f', 'h']

Array filtering

To filter out some values, call Array.filter():

let filteredArr = arr.filter(item => item !== 'x'); // x marks the spot... to be taken out!

Array mapping

Use Array.map() to make array elements contribute their share:

let squaredArr = [1, 2, 3].map(x => x * x); // [1, 4, 9] because Math!

Practical Tips

  • REST API responses often return array-like structures. Before you use array methods on them, convert them using Array.from() or spread syntax (...).
  • To look into an array within an array, use Array.flat() or Array.flatMap().
  • If you're dealing with a big array, take note of performance. For accumulative operations, consider Array.reduce().
  • In a reactive programming background, practicing immutability by creating new arrays instead of modifying existing ones can help to manage side-effects.