How To Use Unshift Method In JavaScript With Example

admin_img Posted By Bajarangi soft , Posted On 25-09-2020

There are several way to add single element or multiple elements to the beginning of an array In java script so today we are going to discuss how to use unshift method In Java Script.

How To Use Unshift Method In JavaScript With Example

The unshift() method adds new items to the beginning of an array, and returns the new length.

Note: This method changes the length of an array.

To add new items at the end of an array, use the push() method.

Syntax and Usage

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

Parameter Values

item1, item2, ..., itemX -> Required. The item(s) to add to the beginning of the array


Let's Start 

Example(1)

1.Create array.
var languages = ["PHP", "JAVASCRIPT", "PYTHON", "C++"];

2.For Existing array now we need to add new elements on click of button 
document.getElementById("demo").innerHTML = languages;

function languages_function() {
    languages.unshift("HTML","CSS");
    document.getElementById("demo").innerHTML = languages;
}


Complete code to adds new items to the beginning of an array, and returns the new length.
<!DOCTYPE html>
<html>
<head>
    <title>adds new items to the beginning of an array, and returns the new length.</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <br>
    <br>
    <div class="text-center">
        <h1>adds new items to the beginning of an array, and returns the new length.</h1>
    </div>
    <br>
    <div class="well">
        <button class="btn btn-primary" onclick="languages_function()">Click it</button>
        <h1 id="demo"></h1>
    </div>
    <br>
</div>
</body>
</html>

<script>
    var languages = ["PHP", "JAVASCRIPT", "PYTHON", "C++"];
    document.getElementById("demo").innerHTML = languages;

    function languages_function() {
        languages.unshift("HTML","CSS");
        document.getElementById("demo").innerHTML = languages;
    }
</script>

 

Related Post