push()

ES3+

Adds one or more elements to the end of an array and returns the new length.

Syntax

array.push(element1, element2, ...)

Parameters

elements any

Elements to add to the end of the array

Return Value

number

The new length of the array

Examples

JavaScript
const fruits = ['apple', 'banana'];
const newLength = fruits.push('cherry');
console.log(fruits);
console.log(newLength);
Output:
// ['apple', 'banana', 'cherry'] 3

📌 When to Use

Use push() when you need to add elements to the end of an array. It's the most common way to build arrays incrementally, implement queues, or collect results from loops.

⚠️ Common Mistakes

Using arr.push([...items]) instead of arr.push(...items) - creates nested array

Expecting push() to return the modified array - it returns the new length

Using push() in React/Vue state directly - use spread instead: [...state, newItem]

✅ Best Practices

For immutable operations, use spread: const newArr = [...arr, newItem]

Push multiple items at once: arr.push(item1, item2, item3) is more efficient

Use push with spread to add array items: arr.push(...otherArr)

⚡ Performance Notes

push() is O(1) amortized - very fast for adding to the end. JavaScript arrays are dynamic, so occasional resizing may occur. For building large arrays, push() is much faster than using concat() or spread in a loop.

🌍 Real World Example

Collecting Form Validation Errors

Build an array of validation errors while checking form fields

function validateForm(data) {
  const errors = [];

  if (!data.email) {
    errors.push('Email is required');
  } else if (!data.email.includes('@')) {
    errors.push('Invalid email format');
  }

  if (!data.password) {
    errors.push('Password is required');
  } else if (data.password.length < 8) {
    errors.push('Password must be at least 8 characters');
  }

  return errors;  // ['Invalid email format', 'Password must be at least 8 characters']
}

Related Methods