This post will discuss how to push an item onto the front of an array in JavaScript.

There are several ways to push an item onto the front of an array in JavaScript. To push an item onto the front of an array, we need to add it to the index 0 and shift the other elements to the right. Here are some of them:

1. Using unshift() function

One common way to push an item onto the front of an array is to use the unshift() function. This function adds one or more elements to the beginning of the array and returns the new length of the array. This function changes the length and the content of the original array, so be careful if we want to preserve the original array. Here’s an example:

Download  Run Code

2. Using concat() function

Another way to push an item onto the front of an array is to use the concat() function. This function does not modify the original array, but creates a new array by concatenating two or more arrays or values. We can use this function to prepend a single element or another array to the original array. For example, we can use the concat() function to append an array with the item we want to insert at the front to the original array, as follows:

Download  Run Code

3. Using spread operator

A third way to push an item onto the front of an array is to use the spread operator (…). This is a new feature in ES6 that allows us to expand an iterable object (such as an array) into a list of individual elements. We can use the spread operator inside an array literal to insert an item in front of an existing array. This also does not modify the original array, but creates a new one. Here’s an example of how we can achieve this:

Download  Run Code

4. Using a custom function

We can also write our own function that takes an array and an item as arguments and returns a new array with the item inserted in front of the original array. We can use a loop or a map function to iterate over the elements of the original array and copy them to a new array after adding the item. The following code illustrates this:

Download  Run Code

That’s all about pushing an item onto the front of an array in JavaScript.