The Need for Prepending
There are several use cases where we need to add elements at the beginning of an existing array. For instance, it is used in creating a history stack or a queue data structure. It is also used when creating a user interface to display a list of items where the most recent item is to be displayed first.
The unshift() Method
array.unshift(element1, ..., elementN)
The unshift() method takes one or more elements to add at the beginning of the array. It can accept any number of arguments, and each argument represents the item to be added to the array.
The unshift() method returns the new length of the modified array, which is equal to the original length plus the number of elements added.
Examples of using unshift()
Here are some examples of using the unshift() method:
Using unshift() with single elements
The following example demonstrates how to use the unshift() method to add a single element to the beginning of an array:
let fruits = ['apple', 'banana', 'orange']; fruits.unshift('mango'); console.log(fruits); // Output: ['mango', 'apple', 'banana', 'orange']
Using unshift() with multiple elements
Adding multiple elements can also be done using the unshift() method:
let numbers = [4, 5, 6]; numbers.unshift(1, 2, 3); console.log(numbers); // Output: [1, 2, 3, 4, 5, 6]
Calling unshift() on non-array objects
If the unshift() method is called on a non-array object, then it will result in a TypeError.
Using the unshift() method is an efficient way to prepend elements to an array as it is a built-in method that has a better time-complexity than other methods such as the splice() method. However, if there are a large number of elements in the array, then the performance may be slower than using other methods such as pushing elements to the end of the array and then reversing the array.
The unshift() method is supported in all modern browsers, including Chrome, Firefox, Safari, Opera, and Microsoft Edge. It is also supported in Internet Explorer 9 and above.