Array unshift() Method - Javascript Array

Javascript examples for Array:unshift

Description

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

This method changes the length of an array.

Syntax

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

Parameter Values

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

Return Value:

A Number, representing the new length of the array

The following code shows how to Add new items to the beginning of an array:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<button onclick="myFunction()">Test</button>

<p id="demo"></p>

<script>
var fruits = ["a","b","c","d","e"];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {//from w  w  w .  j av a2s  .  c om
    fruits.unshift("Lemon", "TEST");
    document.getElementById("demo").innerHTML = fruits;
}
</script>

</body>
</html>

Related Tutorials