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']
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.