AppDividend
Latest Code Tutorials

Javascript Array Unshift Example | Array.prototype.unshift() Tutorial

0

Javascript Array Unshift Example | Array.prototype.unshift() Tutorial is today’s topic. Javascript Array Unshift Example | Array.prototype.unshift() Tutorial. The unshift() method adds one or more items or elements to the beginning of the array and returns the new length of the array. The unshift() method changes the length of the array directly, so it is not a pure function. If we need to add a new item at the end of an array, then we can use the push() method.

If you want to learn more about the latest Javascript tutorials then check out this The Complete Javascript Course 2018.

Javascript Array Unshift Example

When people first start to learn about arrays in javascript then, they usually learn about the push() and pop() methods which merely adds and removes the item from the end of an array. If their particular language supports it. These two methods append the items to the array and remove an element from the array respectively. Both of these methods work at the end of the array, and not at the start of an array, where the index is largest. 

Javascript arrays have the native support for this push () and pop() two methods. Javascript also has support for parallel methods as well that work at the beginning of the array, where the index is smallest. Unshift() and shift() are the same as push() and pop(), only work, at the other end of the array.

The syntax of Javascript Array Unshift is following.

array.unshift(item1, item2, ..., itemX)

Arguments
The number of arguments to this function is the same as the number of elements to be added at the beginning of the array.

Return value
This function returns the new length of the array after inserting the arguments at the beginning of the array.

Let us take a simple example and see how it works. Write the following code in the app.js file. We are using node.js to test the Javascript code.

// app.js

let apps = ["Instagram", "Facebook", "Messanger"];
apps.unshift("Oculus", "WhatsApp");

console.log(apps);

Run the file, and you can see that Oculus and WhatsApp are appended at the start of an array.

 

Javascript Array Unshift Example | Array.prototype.unshift() Tutorial

The following code will include almost all the scenarios of the unshift() method.

let arr = [1, 2];

arr.unshift(0); // result of call is 3, the new array length
// arr is [0, 1, 2]

arr.unshift(-2, -1); // = 5
// arr is [-2, -1, 0, 1, 2]

arr.unshift([-3]);
// arr is [[-3], -2, -1, 0, 1, 2]

Finally, Javascript Array Unshift Example | Array.prototype.unshift() Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.