Add new value to an existing array in JavaScript
⚡TLDR
For a quick append to an array, go with push():
Expanding the array from the start? Not an issue with unshift():
Append Sanely
When you want to deal with array size, avoid new Array(). Stick to []:
Dealing with new Array()
Start your arrays with []. It avoids surprises:
Array-like objects? No problem.
Use Array.prototype.push.call() when wrestling array-like objects:
Handling multiple values
Got multiple new elements? push() has got you covered:
Inserting at a specific index
Use Jedi mind control (aka Array.splice()) for exact insertions at any index:
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 (...):
Array filtering
To filter out some values, call Array.filter():
Array mapping
Use Array.map() to make array elements contribute their share:
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()orArray.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.
Linked
Was this article helpful?