unshift()

The unshift method in JavaScript is utilized to insert one or several elements at the start of a specified array, subsequently returning the modified array. This method alters the length of the initial array.

Syntax

The syntax for the unshift method is outlined as follows:

Example

array. unshift(element1,element2,....,elementn)

Parameter

element1, element2, ..., elementn - The individual elements that are to be included.

Return

The original array with added elements.

JavaScript Array unshift method example

Let's see some examples of unshift method.

Example 1

Here, we will add an element in the given array.

Example

<script>

var arr=["AngularJS","Node.js"];

var result=arr.unshift("JQuery");

document.writeln(arr); 

</script>

Output:

Output

JQuery,AngularJS,Node.js

Example 2

Let’s examine a scenario where we incorporate multiple elements into the specified array.

Example

<script>

var arr=["AngularJS","Node.js"];

document.writeln("Length before invoking unshift(): "+arr.length+"<br>");

arr.unshift("JQuery","Bootstrap");

document.writeln("Length after invoking unshift(): "+arr.length+"<br>"); 

document.writeln("Updated array: "+arr);

</script>

Output:

Output

Length before invoking unshift(): 2

Length after invoking unshift(): 4

Updated array: JQuery,Bootstrap,AngularJS,Node.js

Input Required

This code uses input(). Please provide values below: