How do I append an object (such as a string or number) to an array in JavaScript?
JavaScript provides several methods to append objects to arrays, with the most common being push() to add elements at the end and unshift() to add elements at the beginning. These methods modify the original array and return the new length, while splice() offers more flexible insertion at any position.
Contents
- Basic Array Methods
- Advanced Insertion Techniques
- Performance Considerations
- Immutable Alternatives
- Practical Examples
Basic Array Methods
The push() Method
The push() method is the most straightforward way to append one or more objects to the end of an array. It modifies the original array and returns the new length.
const fruits = ['apple', 'banana'];
const newLength = fruits.push('orange');
console.log(fruits); // ['apple', 'banana', 'orange']
console.log(newLength); // 3
You can also push multiple objects at once:
const colors = ['red', 'blue'];
colors.push('green', 'yellow', 'purple');
console.log(colors); // ['red', 'blue', 'green', 'yellow', 'purple']
The unshift() Method
To append objects to the beginning of an array, use unshift(). This method also modifies the original array and returns the new length.
const numbers = [3, 4, 5];
numbers.unshift(1, 2);
console.log(numbers); // [1, 2, 3, 4, 5]
Note:
unshift()is generally slower thanpush()because it requires shifting all existing elements to make room for the new ones.
Advanced Insertion Techniques
The splice() Method
splice() is the most versatile method for inserting objects into arrays. It allows you to insert elements at any position while optionally removing elements.
const letters = ['a', 'b', 'c'];
// Insert 'x' at index 1
letters.splice(1, 0, 'x');
console.log(letters); // ['a', 'x', 'b', 'c']
// Insert multiple elements
const numbers = [1, 2, 3, 4];
numbers.splice(2, 0, 10, 20, 30);
console.log(numbers); // [1, 2, 10, 20, 30, 3, 4]
The syntax is: array.splice(startIndex, deleteCount, item1, item2, ...)
Using Spread Syntax (ES6+)
Modern JavaScript offers the spread syntax for creating new arrays with appended objects:
const original = [1, 2, 3];
const newArray = [...original, 4, 5];
console.log(newArray); // [1, 2, 3, 4, 5]
// For insertion at specific positions
const modified = [0, ...original];
console.log(modified); // [0, 1, 2, 3]
Performance Considerations
When working with large arrays, performance differences between methods become significant:
| Method | Performance | Best Use Case |
|---|---|---|
push() |
Excellent | Adding elements to the end |
unshift() |
Poor (O(n)) | Adding elements to the beginning |
splice() |
Variable | Inserting at any position |
| Spread syntax | Good | Creating new arrays |
For better performance with large arrays:
- Always prefer
push()when adding to the end - Avoid
unshift()in performance-critical code - Consider using
splice()over spread syntax for in-place modifications
Immutable Alternatives
If you need to maintain immutability (common in React and functional programming):
Using concat()
const original = [1, 2, 3];
const newArray = original.concat(4, 5);
console.log(newArray); // [1, 2, 3, 4, 5]
console.log(original); // [1, 2, 3] (unchanged)
Using the Spread Operator (Immutable)
const original = [1, 2, 3];
const newArray = [...original, 4];
console.log(newArray); // [1, 2, 3, 4]
console.log(original); // [1, 2, 3] (unchanged)
Using Array.prototype.push() with Spread
const state = { items: [1, 2, 3] };
const newState = {
...state,
items: [...state.items, 4]
};
Practical Examples
Adding Objects to an Array
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
];
// Add new user
users.push({ id: 3, name: 'Charlie' });
// Insert at beginning
users.unshift({ id: 0, name: 'David' });
// Insert in middle
users.splice(2, 0, { id: 2.5, name: 'Eve' });
console.log(users);
Batch Operations
const data = [];
// Add multiple items efficiently
data.push({ type: 'event', timestamp: Date.now() });
data.push({ type: 'log', timestamp: Date.now() });
data.push({ type: 'metric', timestamp: Date.now() });
// Or use array of objects
const newItems = [
{ type: 'event', data: 'click' },
{ type: 'event', data: 'scroll' }
];
data.push(...newItems);
Conditional Insertion
const scores = [85, 90, 78, 92];
const newScore = 88;
if (newScore > 75) {
scores.push(newScore);
console.log('Score added:', scores);
}
// Insert in sorted position
const sortedScores = [60, 75, 80, 85, 90];
const insertScore = 82;
for (let i = 0; i < sortedScores.length; i++) {
if (insertScore < sortedScores[i]) {
sortedScores.splice(i, 0, insertScore);
break;
}
}
console.log(sortedScores); // [60, 75, 80, 82, 85, 90]
Conclusion
JavaScript provides several effective methods for appending objects to arrays, each suited for different scenarios. The push() method is optimal for adding elements to the end, unshift() works for beginning insertion, and splice() offers the most flexibility for any position. For modern JavaScript, spread syntax provides a clean and readable alternative. When performance matters with large arrays, prefer push() and avoid unshift(). For immutable operations, use concat() or spread syntax to create new arrays instead of modifying existing ones. Understanding these methods and their performance characteristics will help you write more efficient and maintainable JavaScript code.