unshift() - JavaScript Tutorial

unshift()

BLUF: This tutorial on unshift() provides an in-depth look at JavaScript's core features. It includes practical examples and code snippets to help you master modern JS development.
Key Discovery: unshift()

Understanding unshift() is crucial for building dynamic, interactive web applications. Explore the examples below to see it in action.

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:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience