What are the Alternatives to Using JavaScript's Array.push()?

Learn different ways to add one or more elements to the end of an array

JavaScript's Array.push() adds one or more elements to the end of the array. For example:

const arr = [];
arr.push('foo', 'bar', 'baz');

console.log(arr); // (3) ['foo', 'bar', 'baz']

In this article, we'll show you what alternatives you can use in JavaScript to do the same.

Assigning a Value to the Last Element of Array

Since Array.length is always one more than the last index of the array, we can use it to assign a value to the end of the array, for example, like so:

const arr = [];
arr[arr.length] = 'foo';
arr[arr.length] = 'bar';
arr[arr.length] = 'baz';

console.log(arr); // (2) ['foo', 'bar', 'baz']

Using the Spread Syntax

We can create a new array into which we expand elements of an existing array using the spread syntax, and then, at the end of the array we can append one or more elements. For example:

const arr = [];
const newArr = [ ...arr, 'foo', 'bar', 'baz' ];

console.log(newArr); // (3) ['foo', 'bar', 'baz']

Hope you found this post useful. It was published . Please show your love and support by sharing this post.