The JavaScript `Array.push()` method explained
Tags: webdev, beginners, javascript
Published: 2022-11-24 11:47:39

The `Array.push()` method adds one or more elements to the end of an array and returns the new length of the array.

## Table of Contents

- [How It Works](#how-it-works)
- [Big O Complexity](#big-o-complexity)
- [More Examples](#more-examples)
- [Browser Compatibility](#browser-compatibility)
- [Conclusion](#conclusion)
- [Resources](#resources)

---

## How it works

### Syntax

```js
array.push(element1, ..., elementN)
```

Example:

```js
const numbers = [1, 2, 3];
numbers.push(4);

console.log(numbers); // [1, 2, 3, 4]
```

### Parameters

- element1, ..., elementN
  - The elements to add to the end of the array.

You can pass as many elements as you want to the `Array.push()` method.

### Return value

The `push()` method returns the new length of the array, just like the `array.length` property.

Example:

```js
const sports = ["tennis", "basketball"];
const newLength = sports.push("football", "swimming");

console.log(sports); // ['tennis', 'basketball', 'football', 'swimming']
console.log(newLength); // 4
console.log(sports.length); // 4
```

---

## Big O complexity

Since the `push()` method adds elements to the end of an array, it has a constant time complexity of O(1). This means that the time it takes to add an element to the end of an array is the same regardless of the size of the array.

- Time complexity: O(1)
- Space complexity: O(1)

In contrast, the `unshift()` method, which adds elements to the beginning of an array, has a linear time complexity of O(n). It means that both the time and space complexity of the `unshift()` method depends on the size of the array. Because when a new element is added to the beginning of an array, all the other elements in the array must be shifted over by one index.

---

## More Examples

### Merging two arrays

```js
const array1 = ["a", "b", "c"];
const array2 = ["d", "e", "f"];

array1.push(...array2);

console.log(array1); // ['a', 'b', 'c', 'd', 'e', 'f']
```

You might have noticed that we used the spread operator (`...`) to merge the two arrays. This is because the `push()` method only accepts a list of arguments, not an array. The spread operator allows us to pass an array as a list of arguments.

However, if we had passed the `array2` array directly to the `push()` method, it would have added the array as a single element to the end of the `array1` array. We would get the following result:

```js
array1.push(array2);

console.log(array1); // ['a', 'b', 'c', ['d', 'e', 'f']]
```

### Working with objects

Unfortunately, the `push()` method does not work on objects. If you try to do so, you will get an error, saying that objects do not have a `push()` method.

However, it is possible to use the `push()` method on an array of objects. For example:

```js
const users = [
  { name: "John", age: 25 },
  { name: "Jane", age: 30 },
];

users.push({ name: "Jack", age: 40 });

console.log(users);
// [
//   { name: 'John', age: 25 },
//   { name: 'Jane', age: 30 },
//   { name: 'Jack', age: 40 }
// ]
```

### Stack data structure - inserting elements

A stack is a data structure that follows the LIFO (Last In First Out) principle. Imagine a bunch of books stacked on top of each other. The last book you put on the stack is the first book you can take off the stack.

<figure>
  <img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qnkksvb8lkiri4m0lc14.jpg" alt="A stack of books on a wooden stool">
  <figcaption>
    Photo by <a href="https://www.pexels.com/photo/close-up-photo-of-stack-of-books-on-wooden-stool-4219040/">Karolina Grabowska</a> on <a href="https://www.pexels.com/">Pexels</a>
  </figcaption>
</figure>

This means that we can implement adding the book to the stack using the `push()` method.

```js
const stack = [];

stack.push("book1");
stack.push("book2");

console.log(stack); // ['book1', 'book2']
```

If you're interested in Stack, you can learn more about its implementation in JavaScript in this [article](https://www.geeksforgeeks.org/implementation-stack-javascript/).

---

## Browser compatibility

Since the `push()` method is JavaScript built-in method, it is supported by all modern browsers.

---

## Conclusion

The `Array.push()` method:

- Inserts one or more elements at the end of an array.
- Returns the new length of the array.
- Has a constant time and space complexity of O(1).
- Does not work on objects, but works on an array of objects.
- Can be used to implement a stack data structure.

Hopefully, this article has given you a good understanding of the `Array.push()` method in JavaScript. If you have any questions or suggestions, feel free to leave a comment below. Thanks for reading!

---

## Resources

- [MDN: Array.prototype.push()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push)
- [W3Schools: Array.push()](https://www.w3schools.com/jsref/jsref_push.asp)
- [Can I use: Array.prototype.push()](https://caniuse.com/mdn-javascript_builtins_array_push)