2 Example(s) of JavaScript unshift function


Description :

JavaScript unshift function is used to add value in the beginning of the provided array. we have an array: var arr = [2,5]; arr.unshift(0); will add 0 in the beginning of the array. the final array will be [0, 2,5]. See the code snippet:


JavaScript unshift function Example - 1
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
<button onclick="addElement()">Add element</button>

<p id="sample"></p>

<script>
var arr = [2,5];
document.getElementById("sample").innerHTML = arr ;

function addElement() {
    arr.unshift(0);
    document.getElementById("sample").innerHTML = arr ;
}
</script>
</body>
</html>

Output

Description :

In this example, JavaScript unShift will add -1 and -2 in the beginning of array arr. So the final array will become like [-1,-2,1,2]. See the code snippet:


JavaScript unshift function Example - 2
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
<button onclick="addElement()">Add element</button>

<p id="sample"></p>

<script>
var arr = [1, 2];
document.getElementById("sample").innerHTML = arr;

function addElement() {
      arr.unshift(-1,-2);
      document.getElementById("sample").innerHTML = arr;
    }
</script>
</body>
</html>

Output