javascript
  1. javascript-unshift

JavaScript unshift() Method

The unshift() method is a built-in function in JavaScript that adds one or more elements to the beginning of an array and returns the new length of the array.

Syntax

The syntax for unshift() is:

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

Where array is the array on which the unshift() method is called, element1 to elementN are the elements that you want to add to the beginning of the array.

Example

Consider the following example of the unshift() method:

let fruits = ["banana", "orange", "apple"];
let length = fruits.unshift("grapes", "kiwi");

console.log("New array: " + fruits);
console.log("New length: " + length);

Output

The output of the above example will be:

New array: ["grapes", "kiwi", "banana", "orange", "apple"]
New length: 5

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Array Unshift Example</title>
</head>
<body>

<!-- Placeholder for displaying the output -->
<p id="output"></p>

<script>
    // Array
    let fruits = ['banana', 'orange','apple'];

    // Add elements to the beginning of the array using unshift
    let newLength = fruits.unshift('grape', 'kiwi');

    // Display the modified array and the new length
    document.getElementById("output").innerHTML += "Modified Fruits: " + fruits.join(', ') + "<br>";
    document.getElementById("output").innerHTML += "New Length: " + newLength;
</script>

</body>
</html>
Try Playground

Explanation

In the above example, unshift() adds two new elements grapes and kiwi to the beginning of the fruits array. The unshift() method modifies the original array and returns the new length of the array, which is now 5.

Use

The unshift() method is useful for adding elements to the beginning of an existing array. It is often used in conjunction with the push() method, which adds elements to the end of an array. Together, these methods provide a simple way to manage a dynamic list of items in JavaScript.

Important Points

The following are some important points to keep in mind when using the unshift() method:

  • The unshift() method modifies the original array and returns the new length of the array.
  • It is possible to add one or more elements to the beginning of an array using the unshift() method.
  • The order of the elements added to the array using unshift() is maintained and the added elements are shifted to the right.
  • The unshift() method is not supported in Internet Explorer 8 and earlier versions.

Summary

The unshift() method is a useful built-in function in JavaScript for adding one or more elements to the beginning of an array. It modifies the original array and returns the new length of the array. By using the unshift() method, developers can easily manage lists of elements in their JavaScript applications.

Published on: