WebMasterCampus
WEB DEVELOPER Resources

Javascript Add New Array Elements at the Start of an Array

Learn using Javascript how to add new array elements at the start of an array


The Javascript unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

You can use Javascript shift() method to remove and return the first element of an array.

Syntax unshift()

arr.unshift(element1[, …[, elementN]])

Return Value: The new length property of the object upon which the method was called.

Syntax shift()

arr.shift()

Return value: The removed element from the array; undefined if the array is empty.

Code of unshift Single Value

  <script>
    var a = [30, 40, 50, 400];

    document.getElementById('result1').innerHTML = a;

    a.unshift(20);
    console.log(a);    

  </script>  

Code of unshift Multifple Value

  <script>
    var a = [30, 40, 50, 400];

    console.log(a);

    a.unshift(10,20);    

    console.log(a);
    
    console.log(a.shift()); 
        
  </script>  

Code of shift

shift() method to remove and return the first element of an array.

  <script>
    var a = [30, 40, 50, 400];

    console.log(a);

    console.log(a.shift());    

    console.log(a);
        
  </script>  

References

mozilla.org unshift

mozilla.org shift

Created with love and passion.