How to Add Element to Array in JavaScript: Simple Guide
To add an element to an array in JavaScript, use the
push() method to add at the end or unshift() to add at the beginning. You can also use the spread operator [...array, newElement] to create a new array with the added element.Syntax
Here are common ways to add elements to an array:
array.push(element): Adds element to the end ofarray.array.unshift(element): Adds element to the start ofarray.newArray = [...array, element]: Creates a new array with element added at the end.
javascript
array.push(element); array.unshift(element); newArray = [...array, element];
Example
This example shows how to add elements to an array using push(), unshift(), and the spread operator.
javascript
const fruits = ['apple', 'banana']; // Add to end fruits.push('orange'); console.log(fruits); // ['apple', 'banana', 'orange'] // Add to start fruits.unshift('mango'); console.log(fruits); // ['mango', 'apple', 'banana', 'orange'] // Create new array with added element const newFruits = [...fruits, 'grape']; console.log(newFruits); // ['mango', 'apple', 'banana', 'orange', 'grape']
Output
['apple', 'banana', 'orange']
['mango', 'apple', 'banana', 'orange']
['mango', 'apple', 'banana', 'orange', 'grape']
Common Pitfalls
Common mistakes when adding elements to arrays include:
- Using
push()but expecting a new array returned (it returns the new length, not the array). - Trying to add elements by assigning to an index beyond the current length without filling intermediate spots.
- Mutating arrays unintentionally when you want to keep the original unchanged.
javascript
const arr = [1, 2]; // Wrong: expecting push to return new array const result = arr.push(3); console.log(result); // 3 (new length), not the array // Right: push modifies original array console.log(arr); // [1, 2, 3] // Wrong: skipping indexes arr[5] = 6; console.log(arr); // [1, 2, 3, <2 empty items>, 6]
Output
3
[1, 2, 3]
[1, 2, 3, <2 empty items>, 6]
Quick Reference
Summary of methods to add elements to arrays:
| Method | Description | Modifies Original Array | Returns |
|---|---|---|---|
| push(element) | Adds element to end | Yes | New length of array |
| unshift(element) | Adds element to start | Yes | New length of array |
| spread operator [...array, element] | Creates new array with element at end | No | New array |
| array[index] = element | Adds or replaces element at index | Yes | Assigned element |
Key Takeaways
Use push() to add elements at the end of an array.
Use unshift() to add elements at the beginning of an array.
The spread operator creates a new array without changing the original.
push() returns the new length, not the updated array.
Avoid skipping indexes when assigning elements directly to prevent sparse arrays.