- What is Array.unshift() in JavaScript
- What does Array.unshift() Method Return
- How to Use Array.unshift() Method in JavaScript
So, let’s begin!
What is Array.unshift() in JavaScript
It is a predefined method in JavaScript that is used to insert at least one item at the start of an array and hence increases the array’s length.
Syntax
The basic syntax of the Array.unshift() method is shown in the below-given snippet:
In the above snippet, arrayName is an array while the item1, item2, etc. are the items/elements to be inserted at the start of any specific array.
What does Array.unshift() Method Return
In JavaScript, the unshift() method takes some items as parameters, inserts them at the beginning of the targeted array, and returns a new length of the array(i.e. increased length).
How to Use Array.unshift() Method in JavaScript
As of now, we are done with the theoretical part of the Array.unshift() method. For the clarity of concepts, we will consider a couple of scenarios where we can use the Array.unshift() method.
Example1
In this example, firstly, we will create a numeric array of five elements, and afterward we will insert some new elements at the beginning of that array using the Array.unshift() method:
const size = empAge.unshift(23, 32);
console.log("Array Size: ", size);
console.log("Array Elements: ", empAge);
Initially, we created an array “empAge” of five elements, next, we utilized the unshift method and we passed it two elements and stored it in a variable size. Afterwards, we printed array size and array elements of the browser’s console:
The output shows that the Array.unshift() method returned the new length of the array.
Example2
Let’s consider another example to understand how Array.unshift() method works with the string data:
const size = empNames.unshift("John", "Paul", "Ambrose");
console.log("Array Size: ", size);
console.log("Array Elements: ", empNames);
In this example we utilized the unshift() method to insert three elements “John”, “Paul”, and “Ambrose” at the start of the array.
The output verifies the working of Array.unshift() method.
Conclusion
In JavaScript, the Array.unshift() is a predefined method that takes some items as parameters, inserts them at the beginning of the targeted array, and returns the array’s modified length. The Array.unshift() method is equally effective for both numeric as well as string/alphabetic data. This post explained different aspects of the Array.unshift() method e.g., what is Array.unshift() method, its syntax, and how to use it in JavaScript.